diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..59e57db58d8e157464558da91a1094b0b07481f1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,35 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/2b8f22cca7c5c65e0f21d65339776b4a.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/3a7787cfa10c5bfbd1269e0a9b45ada4.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/4fb2f922a21d1cc3f7384e16bc817fe6.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/89ad03f568856e28c5507b9f1b3fe236.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/a229b2355ab189a8188e9c82c9d3f4dd.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/adcd4d40bbf245ea29ce8d37ae6e2dc3.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/b36dba1f247bc466b79a1ba6e74fc0e7.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/c26a6085d8ad35128a3034aa0b001ec7.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/cb85eaee18ef536bcb713afb29bbb7d4.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/d0777b481e9b691e2428652b0b87cf3a.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Dataset[[:space:]]Images/ee05e18211a38e7b2cd66fc172d388e1.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/dataset_output/LORA_Flat/LORA_001.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/dataset_output/LORA_Skinny/LORA_001.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Example[[:space:]]Faces/392d48ced9a0f1a196e4a685087e5ac5.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Example[[:space:]]Faces/8b16036925ea003fb119a8b523448259.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Example[[:space:]]Faces/9a1ecdb690dba74b2e90bb86a71e38e6.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Example[[:space:]]Faces/c26a6085d8ad35128a3034aa0b001ec7.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Example[[:space:]]Faces/ca8a48fd043663ee4f3e932c5eb33fd2.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Example[[:space:]]Faces/ea2302a9ddb7ea4220fbc142cc00de98.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Example[[:space:]]Faces/fd1b3747c03944a16dde6a22e5ea5640.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/can[[:space:]]you[[:space:]]find[[:space:]]me[[:space:]]in[[:space:]]the[[:space:]]forest[[:space:]](1).jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/can[[:space:]]you[[:space:]]find[[:space:]]me[[:space:]]in[[:space:]]the[[:space:]]forest[[:space:]](2).jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/can[[:space:]]you[[:space:]]find[[:space:]]me[[:space:]]in[[:space:]]the[[:space:]]forest.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/feeling[[:space:]]ethereal[[:space:]]🦋💕.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/I[[:space:]]like[[:space:]]when[[:space:]]you[[:space:]]stare[[:space:]]🧡[[:space:]](1).jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/I[[:space:]]like[[:space:]]when[[:space:]]you[[:space:]]stare[[:space:]]🧡[[:space:]](2).jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/kiss[[:space:]]me[[:space:]]more[[:space:]]💋[[:space:]](2).jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/kiss[[:space:]]me[[:space:]]more[[:space:]]💋[[:space:]](4).jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/example[[:space:]]influencer[[:space:]]images/kiss[[:space:]]me[[:space:]]more[[:space:]]💋.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/nano[[:space:]]banana[[:space:]]2.png filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Tattoos/49f2fc0dbff9bc228392b680db029b27.jpg filter=lfs diff=lfs merge=lfs -text +aiorbust-ofm-pack-main/Tattoos/5d8eafa003576838106a0c4bf08c7052.jpg filter=lfs diff=lfs merge=lfs -text diff --git a/aiorbust-ofm-pack-main/.gitignore b/aiorbust-ofm-pack-main/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3bbe7b6f921890134bd22373cfdd89e91d5e788f --- /dev/null +++ b/aiorbust-ofm-pack-main/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +*.pyo diff --git a/aiorbust-ofm-pack-main/Dataset Images/2b8f22cca7c5c65e0f21d65339776b4a.jpg b/aiorbust-ofm-pack-main/Dataset Images/2b8f22cca7c5c65e0f21d65339776b4a.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3bf8e700a5a0f031ef2eb8b89943a3ef4b9a1700 --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/2b8f22cca7c5c65e0f21d65339776b4a.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0ed1791fa1482975a35152ab6e6f19bd2aa532765ee0573f983bd47e08bd7ec +size 146728 diff --git a/aiorbust-ofm-pack-main/Dataset Images/3a7787cfa10c5bfbd1269e0a9b45ada4.jpg b/aiorbust-ofm-pack-main/Dataset Images/3a7787cfa10c5bfbd1269e0a9b45ada4.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c93caf986013b9ffac7288f7dbd9f1014f5447d9 --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/3a7787cfa10c5bfbd1269e0a9b45ada4.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c33ccea13666b19a8c96fff20080fcb73e3ea3feaf11c0477cf5a2edaa7ceb2 +size 112137 diff --git a/aiorbust-ofm-pack-main/Dataset Images/4140ac46b33e548feda14b0fefc85bcb.jpg b/aiorbust-ofm-pack-main/Dataset Images/4140ac46b33e548feda14b0fefc85bcb.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4eaf598cdb35a3f13c2616488eb9896a3a91dfb3 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/4140ac46b33e548feda14b0fefc85bcb.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/43ee157d566b5aada5a3dcb47fb4afa8.jpg b/aiorbust-ofm-pack-main/Dataset Images/43ee157d566b5aada5a3dcb47fb4afa8.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ec6d9e03431732a780939a884dacf7c4d5919d66 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/43ee157d566b5aada5a3dcb47fb4afa8.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/4fb2f922a21d1cc3f7384e16bc817fe6.jpg b/aiorbust-ofm-pack-main/Dataset Images/4fb2f922a21d1cc3f7384e16bc817fe6.jpg new file mode 100644 index 0000000000000000000000000000000000000000..10b002c18d9d1eae72f263c23d040561606969ca --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/4fb2f922a21d1cc3f7384e16bc817fe6.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39049a002039cf3b548d372ba5d3ebc39970768e42fc4794939b2d4843ad6d22 +size 196501 diff --git a/aiorbust-ofm-pack-main/Dataset Images/557147ab88ff595e5d4ba0e137304454.jpg b/aiorbust-ofm-pack-main/Dataset Images/557147ab88ff595e5d4ba0e137304454.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0feac38e7ff5d1504901ad8ac56b7dc54ca68a32 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/557147ab88ff595e5d4ba0e137304454.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/66730e5442b4c86a386965fa9678246a.jpg b/aiorbust-ofm-pack-main/Dataset Images/66730e5442b4c86a386965fa9678246a.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6e025a5990eb5f86009a12c01e556bf9c7d7cee8 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/66730e5442b4c86a386965fa9678246a.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/69bed9b86d77e264664fff7869050be6.jpg b/aiorbust-ofm-pack-main/Dataset Images/69bed9b86d77e264664fff7869050be6.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3aa95aa8fc02107788c669abc20ec740dafa560e Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/69bed9b86d77e264664fff7869050be6.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/798efdefba3b245397347b2329bfd676.jpg b/aiorbust-ofm-pack-main/Dataset Images/798efdefba3b245397347b2329bfd676.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5d88ddd92fa47c612d0e69233e602c8fb720a822 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/798efdefba3b245397347b2329bfd676.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/89ad03f568856e28c5507b9f1b3fe236.jpg b/aiorbust-ofm-pack-main/Dataset Images/89ad03f568856e28c5507b9f1b3fe236.jpg new file mode 100644 index 0000000000000000000000000000000000000000..dcc132cfa969728e4a99b5d8d0598e9a031d6e49 --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/89ad03f568856e28c5507b9f1b3fe236.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1003c872aaeb306d1d8b4040a260b03359de112287f68c5e2236085e63d0cbf8 +size 116229 diff --git a/aiorbust-ofm-pack-main/Dataset Images/8b39dd90e95c7893c075434326b5cc62.jpg b/aiorbust-ofm-pack-main/Dataset Images/8b39dd90e95c7893c075434326b5cc62.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c68f338d5a8434f728a5cdc203d9bcf4f526a890 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/8b39dd90e95c7893c075434326b5cc62.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/a229b2355ab189a8188e9c82c9d3f4dd.jpg b/aiorbust-ofm-pack-main/Dataset Images/a229b2355ab189a8188e9c82c9d3f4dd.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a4f2425d786524b19837c4d3a3e5b48b78026eee --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/a229b2355ab189a8188e9c82c9d3f4dd.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08336ecbe215dc17ffdc9a7d9766bbae29cf78381388c052a20befbb4e68bf1a +size 100200 diff --git a/aiorbust-ofm-pack-main/Dataset Images/adcd4d40bbf245ea29ce8d37ae6e2dc3.jpg b/aiorbust-ofm-pack-main/Dataset Images/adcd4d40bbf245ea29ce8d37ae6e2dc3.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b30fd5d00ad1637e83b030d135b410e0226c25f4 --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/adcd4d40bbf245ea29ce8d37ae6e2dc3.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5c2b35c0e9f584bc1d2090a2eba9a465356c82b2baf2619ac5908d476eb7ad4 +size 180395 diff --git a/aiorbust-ofm-pack-main/Dataset Images/b16eb5e209202daa432b94e25959e5df.jpg b/aiorbust-ofm-pack-main/Dataset Images/b16eb5e209202daa432b94e25959e5df.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d78a9752b579093b6e9990e6a997f4c177ec66e5 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/b16eb5e209202daa432b94e25959e5df.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/b36dba1f247bc466b79a1ba6e74fc0e7.jpg b/aiorbust-ofm-pack-main/Dataset Images/b36dba1f247bc466b79a1ba6e74fc0e7.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0fbbf0fc4584757f714cd29569b7af24d7644bbe --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/b36dba1f247bc466b79a1ba6e74fc0e7.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d556cbbf0b9adea0e5725793a06c4b49d6f4a0868a0d502dfe2244910fdafd5 +size 110202 diff --git a/aiorbust-ofm-pack-main/Dataset Images/b4bfd0bd35af867d1cdfdf900f72862a.jpg b/aiorbust-ofm-pack-main/Dataset Images/b4bfd0bd35af867d1cdfdf900f72862a.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2b95694a801009fe280010880ae38998efdf669a Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/b4bfd0bd35af867d1cdfdf900f72862a.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/c26a6085d8ad35128a3034aa0b001ec7.jpg b/aiorbust-ofm-pack-main/Dataset Images/c26a6085d8ad35128a3034aa0b001ec7.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5423751165e3e1e1a432421e9738d7951cd00188 --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/c26a6085d8ad35128a3034aa0b001ec7.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bc699d7c6ef77b956b0b6ef971a40eb522675089a3a818b2355ad393eb7734b +size 132698 diff --git a/aiorbust-ofm-pack-main/Dataset Images/cb85eaee18ef536bcb713afb29bbb7d4.jpg b/aiorbust-ofm-pack-main/Dataset Images/cb85eaee18ef536bcb713afb29bbb7d4.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6dbfa580be33dbf3ac3adca7f4af512b4bc10739 --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/cb85eaee18ef536bcb713afb29bbb7d4.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:502df9f007b66ace821ba5d8461ba0a9c580e3d8bc10d3bea788df918d8e9c4d +size 102059 diff --git a/aiorbust-ofm-pack-main/Dataset Images/d0777b481e9b691e2428652b0b87cf3a.jpg b/aiorbust-ofm-pack-main/Dataset Images/d0777b481e9b691e2428652b0b87cf3a.jpg new file mode 100644 index 0000000000000000000000000000000000000000..75c719d15739e5d7bced8e7be843e09f2af4aead --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/d0777b481e9b691e2428652b0b87cf3a.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a4b17c153087fea04de63947ae6c414a8af5a0113b63df614dadc2e0c1386a5 +size 170972 diff --git a/aiorbust-ofm-pack-main/Dataset Images/e389100aba8793f91cf7f03323f66100.jpg b/aiorbust-ofm-pack-main/Dataset Images/e389100aba8793f91cf7f03323f66100.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7acbaf51abbe586d8c6431873ab8f88436ce4f72 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/e389100aba8793f91cf7f03323f66100.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/e7bf042c20ca4000301dac977087e344.jpg b/aiorbust-ofm-pack-main/Dataset Images/e7bf042c20ca4000301dac977087e344.jpg new file mode 100644 index 0000000000000000000000000000000000000000..23b6d2e489843784f51f872e20fc601e06098992 Binary files /dev/null and b/aiorbust-ofm-pack-main/Dataset Images/e7bf042c20ca4000301dac977087e344.jpg differ diff --git a/aiorbust-ofm-pack-main/Dataset Images/ee05e18211a38e7b2cd66fc172d388e1.jpg b/aiorbust-ofm-pack-main/Dataset Images/ee05e18211a38e7b2cd66fc172d388e1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4eb777dc5910b346855051e7cf421814b1b67fd6 --- /dev/null +++ b/aiorbust-ofm-pack-main/Dataset Images/ee05e18211a38e7b2cd66fc172d388e1.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3ec814f13919332a1a2c5b9f7c4dd253b2d6e9a56a5970ecd3450fc5040a491 +size 106357 diff --git a/aiorbust-ofm-pack-main/Example Faces/1a056bdce17022bfd6999f03945543ff.jpg b/aiorbust-ofm-pack-main/Example Faces/1a056bdce17022bfd6999f03945543ff.jpg new file mode 100644 index 0000000000000000000000000000000000000000..78f2b5949f70e2cab00d0be885235d43b86e5648 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/1a056bdce17022bfd6999f03945543ff.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/392d48ced9a0f1a196e4a685087e5ac5.jpg b/aiorbust-ofm-pack-main/Example Faces/392d48ced9a0f1a196e4a685087e5ac5.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a0889619e51421a03b774489ec9daa5dc506e212 --- /dev/null +++ b/aiorbust-ofm-pack-main/Example Faces/392d48ced9a0f1a196e4a685087e5ac5.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1acf3af4a568ba4704fe44ef4604c77874088fa730f29934e718f227157daa7 +size 107052 diff --git a/aiorbust-ofm-pack-main/Example Faces/75563368a304d1fec5a9f033aa97880d.jpg b/aiorbust-ofm-pack-main/Example Faces/75563368a304d1fec5a9f033aa97880d.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b8dbf9432ba3d2b326da1c792144e0be6cf746d0 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/75563368a304d1fec5a9f033aa97880d.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/8b16036925ea003fb119a8b523448259.jpg b/aiorbust-ofm-pack-main/Example Faces/8b16036925ea003fb119a8b523448259.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6a9f4ae3a834f2a5405867bd1b3bea86b82550a7 --- /dev/null +++ b/aiorbust-ofm-pack-main/Example Faces/8b16036925ea003fb119a8b523448259.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b523c2edf1ffcda0b171266aeb877fa30100f4b46eed4dd6bf2e45b510fdfe35 +size 111943 diff --git a/aiorbust-ofm-pack-main/Example Faces/9a1ecdb690dba74b2e90bb86a71e38e6.jpg b/aiorbust-ofm-pack-main/Example Faces/9a1ecdb690dba74b2e90bb86a71e38e6.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4a65f1435768927ad058bc5c9cb78724b0582a96 --- /dev/null +++ b/aiorbust-ofm-pack-main/Example Faces/9a1ecdb690dba74b2e90bb86a71e38e6.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd97b24c5dd40cedb2a2e4ca9b923d02351b5727d65d2be26c4e8f0bdc45dfaa +size 113723 diff --git a/aiorbust-ofm-pack-main/Example Faces/a934f7b2cd16c41d1a775d4e955e87af.jpg b/aiorbust-ofm-pack-main/Example Faces/a934f7b2cd16c41d1a775d4e955e87af.jpg new file mode 100644 index 0000000000000000000000000000000000000000..11d82cc451262d44e823630d68cdd19e1f4471e8 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/a934f7b2cd16c41d1a775d4e955e87af.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/b16eb5e209202daa432b94e25959e5df.jpg b/aiorbust-ofm-pack-main/Example Faces/b16eb5e209202daa432b94e25959e5df.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d78a9752b579093b6e9990e6a997f4c177ec66e5 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/b16eb5e209202daa432b94e25959e5df.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/bcef8092ce8d4b4646c58dc8bd196c63.jpg b/aiorbust-ofm-pack-main/Example Faces/bcef8092ce8d4b4646c58dc8bd196c63.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e3a0cdb1f0efd0df999f7045c489fe9ec971363b Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/bcef8092ce8d4b4646c58dc8bd196c63.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/c26a6085d8ad35128a3034aa0b001ec7.jpg b/aiorbust-ofm-pack-main/Example Faces/c26a6085d8ad35128a3034aa0b001ec7.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5423751165e3e1e1a432421e9738d7951cd00188 --- /dev/null +++ b/aiorbust-ofm-pack-main/Example Faces/c26a6085d8ad35128a3034aa0b001ec7.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bc699d7c6ef77b956b0b6ef971a40eb522675089a3a818b2355ad393eb7734b +size 132698 diff --git a/aiorbust-ofm-pack-main/Example Faces/c8288f2ceb488d300b075947bd86feb1.jpg b/aiorbust-ofm-pack-main/Example Faces/c8288f2ceb488d300b075947bd86feb1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6d252c2972f5d9eadb12a91160d1972ab677be93 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/c8288f2ceb488d300b075947bd86feb1.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/ca8a48fd043663ee4f3e932c5eb33fd2.jpg b/aiorbust-ofm-pack-main/Example Faces/ca8a48fd043663ee4f3e932c5eb33fd2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..54bf86d539bc03504a6c1cfa90a61b1ec8a705dd --- /dev/null +++ b/aiorbust-ofm-pack-main/Example Faces/ca8a48fd043663ee4f3e932c5eb33fd2.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:770dbcde35db4a38df93709b231ad3fac2d1ea47df3faf52f30cc8fd2dbc5c37 +size 163072 diff --git a/aiorbust-ofm-pack-main/Example Faces/cf63397bd45e32541178921182357e25.jpg b/aiorbust-ofm-pack-main/Example Faces/cf63397bd45e32541178921182357e25.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2ed34955d8baa5f5278fc9484427f91af8802bd6 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/cf63397bd45e32541178921182357e25.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/ea2302a9ddb7ea4220fbc142cc00de98.jpg b/aiorbust-ofm-pack-main/Example Faces/ea2302a9ddb7ea4220fbc142cc00de98.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6175798f9475a78b4f95dd42f5b47ca6bfd46615 --- /dev/null +++ b/aiorbust-ofm-pack-main/Example Faces/ea2302a9ddb7ea4220fbc142cc00de98.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3eeda9057385e6a25e813301a0f99dbf98f65c95719f98544860aaf4e1752ed4 +size 227392 diff --git a/aiorbust-ofm-pack-main/Example Faces/f33a36302bba4c005896c205242135c5.jpg b/aiorbust-ofm-pack-main/Example Faces/f33a36302bba4c005896c205242135c5.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d248a477ee6a5f45261055c4cf4a00895ca4fcb1 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/f33a36302bba4c005896c205242135c5.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/f92c11a3eb8141a5a443c17ee1a0fe1a.jpg b/aiorbust-ofm-pack-main/Example Faces/f92c11a3eb8141a5a443c17ee1a0fe1a.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9cb4163a343e080e0a014f22182e5e2e6d95e622 Binary files /dev/null and b/aiorbust-ofm-pack-main/Example Faces/f92c11a3eb8141a5a443c17ee1a0fe1a.jpg differ diff --git a/aiorbust-ofm-pack-main/Example Faces/fd1b3747c03944a16dde6a22e5ea5640.jpg b/aiorbust-ofm-pack-main/Example Faces/fd1b3747c03944a16dde6a22e5ea5640.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a7accefc5f6e5f6f6270e0523e8fd13b61ff48c3 --- /dev/null +++ b/aiorbust-ofm-pack-main/Example Faces/fd1b3747c03944a16dde6a22e5ea5640.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4871ce328f9c47d16358cf56db75fabb6e4feced771ccea3b457195a114b0f4a +size 114164 diff --git a/aiorbust-ofm-pack-main/NODES.md b/aiorbust-ofm-pack-main/NODES.md new file mode 100644 index 0000000000000000000000000000000000000000..2d4330f30050a89165e5b36bc6d46531866ea46f --- /dev/null +++ b/aiorbust-ofm-pack-main/NODES.md @@ -0,0 +1,345 @@ +# Aiorbust OFM Pack (Monthly) - Node Documentation + +## Table of Contents + +1. [Nano Banana Pro Edit](#nano-banana-pro-edit) +2. [Nano Banana 2 Edit](#nano-banana-2-edit) +3. [Seedream 4.5 Edit (Wavespeed)](#seedream-45-edit-wavespeed) +4. [Seedream 4.5 Edit (fal.ai)](#seedream-45-edit-falai) +5. [Prompt Generator](#prompt-generator) +6. [Prompt Selector](#prompt-selector) +7. [Directory Image Loader](#directory-image-loader) +8. [Video Frame Extractor](#video-frame-extractor) +9. [Lora Caption Generator](#lora-caption-generator) +10. [Remove Image Metadata](#remove-image-metadata) +11. [Save as Phone Photo](#save-as-phone-photo) +12. [Load API Keys](#load-api-keys) + +--- + +## Nano Banana Pro Edit + +**Display Name:** Aiorbust Nano Banana Pro Edit +**Category:** image + +Edits or generates images using the Google Gemini 3 Pro image model. Accepts one or more input images along with a text prompt to guide the edit. Automatically detects aspect ratio from the input image when set to "auto". + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| images | IMAGE | Yes | — | Input image(s) to edit | +| api_key | STRING | Yes | — | Google Gemini API key | +| prompt | STRING | Yes | — | Text instruction describing the desired edit | +| aspect_ratio | Dropdown | No | auto | `auto`, `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` | +| image_size | Dropdown | No | 2K | `1K`, `2K`, `4K` | +| temperature | FLOAT | No | 1.0 | Creativity control (0.0 - 2.0) | +| seed | INT | No | 0 | Random seed for reproducibility | +| safety_threshold | Dropdown | No | OFF | Content safety filter level | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| image | IMAGE | The edited/generated image | + +--- + +## Nano Banana 2 Edit + +**Display Name:** Aiorbust Nano Banana 2 Edit +**Category:** image + +Edits images using the Google Gemini 3.1 Flash image model. Faster than Nano Banana Pro but with a smaller model. Defaults to 1K output resolution. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| images | IMAGE | Yes | — | Input image(s) to edit | +| api_key | STRING | Yes | — | Google Gemini API key | +| prompt | STRING | Yes | — | Text instruction describing the desired edit | +| aspect_ratio | Dropdown | No | auto | `auto`, `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` | +| image_size | Dropdown | No | 1K | `1K`, `2K`, `4K` | +| temperature | FLOAT | No | 1.0 | Creativity control (0.0 - 2.0, step 0.05) | +| seed | INT | No | 0 | Random seed for reproducibility | +| safety_threshold | Dropdown | No | OFF | Content safety filter level | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| image | IMAGE | The edited/generated image | + +--- + +## Seedream 4.5 Edit (Wavespeed) + +**Display Name:** Aiorbust Seedream 4.5 Edit(Wavespeed) +**Category:** image + +Edits images using ByteDance's Seedream 4.5 model hosted on WaveSpeed API. Supports 1-10 reference images for context-aware editing with facial feature, lighting, and color tone preservation. Can output up to 4 images per run. When size is set to "auto", it scales the input aspect ratio to approximately 2K resolution. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| images | IMAGE | Yes | — | 1-10 reference images | +| wavespeed_apikey | STRING | Yes | — | WaveSpeed API key | +| prompt | STRING | Yes | — | Text instruction for the edit | +| size | Dropdown | No | auto — match input (2K) | Preset sizes: auto, square 1:1, landscape 4:3, portrait 3:4, portrait 4:5, landscape 5:4, landscape 16:9, portrait 9:16 | +| num_images | INT | No | 1 | Number of output images (1-4) | +| use_custom_size | BOOLEAN | No | False | Enable custom width/height instead of presets | +| custom_width | INT | No | 2048 | Custom output width (512-8192, step 64) | +| custom_height | INT | No | 2048 | Custom output height (512-8192, step 64) | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| image | IMAGE | Edited image(s) as a batch tensor | + +--- + +## Seedream 4.5 Edit (fal.ai) + +**Display Name:** Aiorbust Seedream 4.5 Edit(fal.ai) +**Category:** image + +Same Seedream 4.5 model as above but hosted on fal.ai. Functionally identical with a different API backend. Use this if you have a fal.ai API key instead of WaveSpeed. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| images | IMAGE | Yes | — | 1-10 reference images | +| fal_apikey | STRING | Yes | — | fal.ai API key | +| prompt | STRING | Yes | — | Text instruction for the edit | +| size | Dropdown | No | auto — match input (2K) | Preset sizes (same options as WaveSpeed version) | +| num_images | INT | No | 1 | Number of output images (1-4) | +| use_custom_size | BOOLEAN | No | False | Enable custom width/height instead of presets | +| custom_width | INT | No | 2048 | Custom output width (512-8192, step 64) | +| custom_height | INT | No | 2048 | Custom output height (512-8192, step 64) | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| image | IMAGE | Edited image(s) as a batch tensor | + +--- + +## Prompt Generator + +**Display Name:** Aiorbust Prompt Generator +**Category:** utils + +Generates prompts using Gemini or Grok LLMs. Supports 6 modes: JSON image analysis (detailed visual breakdown), style transfer prompt extraction, 4 Seedream Edit configurations for multi-face/body reference workflows, and a custom prompt mode. Can optionally analyze input images. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| mode | Dropdown | Yes | JSON Image Analysis | `JSON Image Analysis`, `Style Transfer Prompt`, `Seedream Edit (2 face + 1 ref)`, `Seedream Edit (1 face + 1 ref)`, `Seedream Edit (2 face and body + 1 ref)`, `Seedream Edit (2 faces + 2 bodies + 1ref)`, `Custom Prompt` | +| provider | Dropdown | Yes | Gemini | `Gemini` or `Grok` | +| gemini_api_key | STRING | No | — | Google Gemini API key (required when provider is Gemini) | +| grok_api_key | STRING | No | — | xAI Grok API key (required when provider is Grok) | +| images | IMAGE | No | — | Input images for analysis | +| custom_prompt | STRING | No | — | Custom instruction text (used in Custom Prompt mode) | +| gemini_model | Dropdown | No | gemini-2.5-pro | `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.0-flash` | +| grok_model | Dropdown | No | grok-4.20-0309-reasoning | Various Grok models (reasoning and non-reasoning variants) | +| temperature | FLOAT | No | 1.0 | Creativity control (0.0 - 2.0) | +| max_tokens | INT | No | 8192 | Maximum output length (64 - 65536) | +| safety_threshold | Dropdown | No | BLOCK_ONLY_HIGH | Content safety filter level | +| seed | INT | No | 0 | Random seed | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| prompt | STRING | The generated prompt text | + +--- + +## Prompt Selector + +**Display Name:** Aiorbust Prompt Selector +**Category:** utils + +Select from pre-written example prompts stored in text files, or type your own. Prompts are loaded from `.txt` files in the `prompts/` directory (separated by `---` delimiters). If user-provided text is entered, it takes priority over the selected example. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| prompt_file | Dropdown | Yes | — | Select a prompt file or "Pose and Style Transfer Prompts" | +| example_prompt | Dropdown | Yes | — | Select a specific prompt from the loaded file | +| prompt_text | STRING | Yes | — | Custom prompt text (overrides selection if non-empty) | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| prompt | STRING | The selected or typed prompt | + +--- + +## Directory Image Loader + +**Display Name:** Aiorbust Directory Image Loader +**Category:** image + +Loads images one at a time from a folder, auto-incrementing through all files. Designed for batch workflows — automatically queues the next image after each run. Supports both relative paths (subfolders of ComfyUI/input/) and absolute paths. + +Supported formats: `.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp`, `.tiff`, `.tif` + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| use_absolute_path | BOOLEAN | Yes | False | Toggle between input subfolder or absolute path | +| run_count | INT | Yes | 1 | Controls which image index to load (auto-increments) | +| input_folder | Dropdown | No | — | Subfolder within ComfyUI/input/ | +| absolute_path | STRING | No | — | Full path to an image directory | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| image | IMAGE | The loaded image tensor | +| filename | STRING | Name of the current file | +| filepath | STRING | Full path to the current file | +| current_index | INT | Current image index (1-based) | +| total_count | INT | Total number of images in the folder | + +--- + +## Video Frame Extractor + +**Display Name:** Aiorbust Video Frame Extractor +**Category:** image + +Extracts frames from video files using PyAV. Upload a video to ComfyUI's input folder, choose a start time and frame count, and select which extracted frame to output. Includes a preview button in the UI to browse frames visually. + +Supported formats: `.mp4`, `.avi`, `.mov`, `.mkv`, `.webm`, `.flv`, `.wmv`, `.m4v` + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| video | Dropdown | Yes | — | Video file from ComfyUI/input/ (supports upload) | +| start_second | FLOAT | Yes | 0.0 | Start time in seconds (0 - 86400) | +| frame_count | INT | Yes | 10 | Number of frames to extract (1 - 9999) | +| frame_interval | INT | Yes | 1 | Sample every Nth frame (1 - 300) | +| selected_frame | INT | Yes | 0 | Which extracted frame to use as output (0 - 9998) | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| image | IMAGE | The selected frame as an image tensor | + +--- + +## Lora Caption Generator + +**Display Name:** Aiorbust Lora Caption Generator +**Category:** image + +Generates LoRA training captions for images using Gemini or Grok vision APIs. Creates a `.txt` caption file per image with the same filename. Designed to work with the Directory Image Loader for batch captioning. Optionally prepends a trigger word to each caption. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| image | IMAGE | Yes | — | Input image to caption | +| filename | STRING | Yes | — | Filename (must be connected from another node) | +| api_key | STRING | Yes | — | Gemini or Grok API key | +| provider | Dropdown | Yes | gemini | `gemini` or `grok` | +| trigger_word | STRING | Yes | — | Word prepended to each caption (e.g. "ohwx") | +| output_folder_name | STRING | Yes | lora_captions | Subfolder name in ComfyUI/output/ | +| gemini_model | Dropdown | No | gemini-2.5-flash | Gemini model to use | +| grok_model | Dropdown | No | grok-2-vision-latest | Grok model to use | +| caption_instruction | STRING | No | (detailed default) | Custom instruction for the vision model | +| temperature | FLOAT | No | 0.7 | Creativity control (0.0 - 2.0) | +| max_tokens | INT | No | 512 | Maximum caption length (64 - 4096) | +| overwrite_existing | BOOLEAN | No | False | Whether to overwrite existing caption files | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| caption | STRING | The generated caption text | +| caption_filepath | STRING | Path to the saved .txt file | + +--- + +## Remove Image Metadata + +**Display Name:** Aiorbust Remove Image Metadata +**Category:** image + +Batch-strips all metadata (EXIF, XMP, PNG chunks, ICC profiles, C2PA) from images in a folder and re-saves them as clean JPEGs. Optionally adds subtle noise to further break any steganographic fingerprints. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| folder | Dropdown | Yes | — | Subfolder within ComfyUI/input/ | +| filename_prefix | STRING | Yes | ComfyUI | Prefix for output filenames | +| output_folder | STRING | Yes | cleaned | Subfolder name in ComfyUI/output/ | +| quality | INT | Yes | 93 | JPEG quality (1-100) | +| add_noise | BOOLEAN | No | True | Add subtle noise to break fingerprints | + +### Outputs + +None (output node only). Saves cleaned images to `ComfyUI/output//`. + +--- + +## Save as Phone Photo + +**Display Name:** Aiorbust Save as Phone Photo +**Category:** image + +Batch-saves images with realistic phone camera EXIF metadata. Supports iPhone 15/16 Pro Max and Samsung Galaxy S24/S25 Ultra with authentic device-specific EXIF data (make, model, software version, focal length, f-number, ISO, exposure). Optionally adds GPS coordinates and subtle noise. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| folder | Dropdown | Yes | — | Subfolder within ComfyUI/input/ | +| filename_prefix | STRING | Yes | ComfyUI | Prefix for output filenames | +| phone_model | Dropdown | Yes | — | `iPhone 15 Pro Max`, `iPhone 16 Pro Max`, `Samsung Galaxy S24 Ultra`, `Samsung Galaxy S25 Ultra` | +| resolution | Dropdown | Yes | 12MP | `12MP`, `48MP/50MP`, `Original` | +| gps_location | Dropdown | Yes | Random US City | `None`, `New York`, `Los Angeles`, `London`, `Tokyo`, `Paris`, `Sydney`, `Dubai`, `Random US City` | +| output_folder | STRING | Yes | phone_photos | Subfolder name in ComfyUI/output/ | +| quality | INT | Yes | 95 | JPEG quality (1-100) | +| add_noise | BOOLEAN | No | True | Add subtle noise for realism | + +### Outputs + +None (output node only). Saves images to `ComfyUI/output//`. + +--- + +## Load API Keys + +**Display Name:** Aiorbust Load API Keys +**Category:** utils + +Simple utility node to enter API keys once and wire them to multiple nodes that need authentication. Avoids duplicating keys across your workflow. + +### Inputs + +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| gemini_api_key | STRING | Yes | — | Google Gemini API key | +| wavespeed_api_key | STRING | Yes | — | WaveSpeed API key | + +### Outputs + +| Name | Type | Description | +|------|------|-------------| +| gemini_api_key | STRING | Pass-through Gemini key | +| wavespeed_api_key | STRING | Pass-through WaveSpeed key | diff --git a/aiorbust-ofm-pack-main/Node.py b/aiorbust-ofm-pack-main/Node.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9eb62e86a56cac08cd98e4d916d30bcf19402b --- /dev/null +++ b/aiorbust-ofm-pack-main/Node.py @@ -0,0 +1,703 @@ +""" +ComfyUI custom nodes for Nano Banana Pro and Nano Banana 2 APIs. +- Nano Banana Pro Edit: edit with images (Gemini 3 Pro). +- Nano Banana 2 Edit: edit with images (Gemini 3.1 Flash). +Each node returns image as ComfyUI IMAGE tensor [B, H, W, C]. +""" + +import logging +import io +import base64 +import random as _random + +import requests +import torch +import numpy as np +from PIL import Image + + +_SAFETY_THRESHOLDS = [ + "OFF", + "BLOCK_NONE", + "BLOCK_ONLY_HIGH", + "BLOCK_MEDIUM_AND_ABOVE", + "BLOCK_LOW_AND_ABOVE", +] + +_HARM_CATEGORIES = ( + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +) + +_ASPECT_RATIOS = [ + "auto", "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", +] + +_IMAGE_SIZES = ["1K", "2K", "4K"] + + +# ---------- Nano Banana Pro Edit ---------- + +class NanoBananaProEditAPINode: + """Edit/Generate images via Gemini 3 Pro (gemimg.py reference implementation).""" + + MODEL_ID = "gemini-3-pro-image-preview" + BASE_URL = "https://generativelanguage.googleapis.com/v1beta/models" + _cached_api_key = "" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "api_key": ("STRING", {"default": "", "multiline": False}), + "prompt": ("STRING", {"default": "", "multiline": True}), + }, + "optional": { + "aspect_ratio": (_ASPECT_RATIOS, {"default": "auto"}), + "image_size": (_IMAGE_SIZES, {"default": "2K"}), + "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True}), + "safety_threshold": (_SAFETY_THRESHOLDS, {"default": "OFF"}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "edit" + CATEGORY = "image" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def edit(self, images, api_key, prompt, aspect_ratio="auto", image_size="2K", temperature=1.0, seed=0, safety_threshold="OFF"): + if api_key.strip(): + NanoBananaProEditAPINode._cached_api_key = api_key.strip() + api_key = api_key.strip() or NanoBananaProEditAPINode._cached_api_key + if not api_key: + raise RuntimeError("Nano Banana Pro: API key is required.") + + # Build parts: images first, then text (matching gemimg.py order) + parts = _images_to_parts(images) + parts.append({"text": prompt.strip()}) + + # Auto aspect ratio detection + if aspect_ratio == "auto": + h, w = images.shape[1], images.shape[2] + ratio = w / h + ratios = { + "1:1": 1.0, "2:3": 0.66, "3:2": 1.5, "3:4": 0.75, "4:3": 1.33, + "4:5": 0.8, "5:4": 1.25, "9:16": 0.56, "16:9": 1.77, "21:9": 2.33, + } + aspect_ratio = min(ratios, key=lambda k: abs(ratios[k] - ratio)) + + # Build payload matching gemimg.py structure exactly + payload = { + "generationConfig": { + "temperature": temperature, + "imageConfig": { + "aspectRatio": aspect_ratio, + "imageSize": image_size, + }, + "responseModalities": ["Image"], + }, + "contents": [{"parts": parts}], + "system_instruction": { + "parts": [{ + "text": "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." + }] + }, + "safetySettings": [ + {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF"}, + {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "OFF"}, + {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "OFF"}, + {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "OFF"}, + ], + } + + # Use x-goog-api-key header (matching gemimg.py) + headers = { + "Content-Type": "application/json", + "x-goog-api-key": api_key, + } + url = f"{self.BASE_URL}/{self.MODEL_ID}:generateContent" + + try: + response = requests.post(url, json=payload, headers=headers, timeout=180) + data = response.json() + except requests.exceptions.RequestException as e: + raise RuntimeError(f"Nano Banana Pro request error: {e}") + + # Check for API error + if "error" in data: + err = data["error"] + raise RuntimeError(f"Nano Banana Pro API error: {err.get('code')} — {err.get('message')}") + + # Check for blocked content + candidates = data.get("candidates", []) + if not candidates: + raise RuntimeError("Nano Banana Pro: no candidates in response.") + + candidate = candidates[0] + finish_reason = candidate.get("finishReason", "") + if finish_reason in ("PROHIBITED_CONTENT", "NO_IMAGE"): + raise RuntimeError(f"Nano Banana Pro: image not generated due to {finish_reason}.") + + if "content" not in candidate: + raise RuntimeError("Nano Banana Pro: no content in response.") + + # Extract inline image data + response_parts = candidate["content"]["parts"] + for part in response_parts: + if "inlineData" in part: + img_bytes = base64.b64decode(part["inlineData"]["data"]) + return _image_bytes_to_tensor(img_bytes, "Nano Banana Pro") + + raise RuntimeError("Nano Banana Pro: no image found in response parts.") + + +# ---------- Nano Banana 2 Edit ---------- + +class NanoBanana2EditAPINode: + """Edit images via Gemini 3.1 Flash API.""" + + MODEL_ID = "gemini-3.1-flash-image-preview" + BASE_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL_ID}:generateContent" + _cached_api_key = "" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "api_key": ("STRING", {"default": "", "multiline": False}), + "prompt": ("STRING", {"default": "", "multiline": True}), + }, + "optional": { + "aspect_ratio": (_ASPECT_RATIOS, {"default": "auto"}), + "image_size": (_IMAGE_SIZES, {"default": "1K"}), + "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True}), + "safety_threshold": (_SAFETY_THRESHOLDS, {"default": "OFF"}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "edit" + CATEGORY = "image" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def edit(self, images, api_key, prompt, aspect_ratio="auto", image_size="1K", temperature=1.0, seed=0, safety_threshold="OFF"): + if api_key.strip(): + NanoBanana2EditAPINode._cached_api_key = api_key.strip() + api_key = api_key.strip() or NanoBanana2EditAPINode._cached_api_key + if not api_key: + raise RuntimeError("Nano Banana 2 Edit: API key is required.") + if images.shape[0] == 0: + raise RuntimeError("Nano Banana 2 Edit: at least one image is required.") + + parts = _images_to_parts(images) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "seed": seed, + } + if image_config: + gen_config["imageConfig"] = image_config + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": { + "parts": [{ + "text": "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." + }] + }, + "generationConfig": gen_config, + "safetySettings": [ + {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF"}, + {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "OFF"}, + {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "OFF"}, + {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "OFF"}, + ], + } + + url = f"{self.BASE_URL}?key={api_key}" + try: + response = requests.post(url, json=payload, headers={"Content-Type": "application/json"}, timeout=120) + response.raise_for_status() + data = response.json() + except requests.exceptions.HTTPError as e: + raise RuntimeError(_api_error_msg("Nano Banana 2 Edit", e)) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"Nano Banana 2 Edit request error: {e!s}") + + raw = _extract_image_from_gemini_response(data, "Nano Banana 2 Edit") + if not raw: + detail = _gemini_response_summary(data) + raise RuntimeError(f"Nano Banana 2 Edit: no image in response. {detail}") + return _image_bytes_to_tensor(raw, "Nano Banana 2 Edit") + + +# ---------- Seedream 4.5 Edit (WaveSpeed) ---------- + +import time as _time + +_SEEDREAM_SIZES = [ + "auto — match input (2K)", + "1920*1920 — square (1:1)", + "2560*1920 — landscape_4_3 (4:3)", + "1920*2560 — portrait_4_3 (3:4)", + "1536*1920 — portrait_4_5 (4:5)", + "1920*1536 — landscape_5_4 (5:4)", + "2560*1440 — landscape_16_9 (16:9)", + "1440*2560 — portrait_16_9 (9:16)", +] + + +class SeedreamEditAPINode: + """Edit images via ByteDance Seedream 4.5 Edit on WaveSpeed API. + + Supports 1-10 reference images for context-aware editing with + facial feature, lighting, and color tone preservation up to 4K. + """ + + BASE_URL = "https://api.wavespeed.ai/api/v3/bytedance/seedream-v4.5/edit" + _cached_api_key = "" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "wavespeed_apikey": ("STRING", {"default": "", "multiline": False}), + "prompt": ("STRING", {"default": "", "multiline": True}), + }, + "optional": { + "size": (_SEEDREAM_SIZES, {"default": "auto — match input (2K)"}), + "num_images": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1}), + "use_custom_size": ("BOOLEAN", {"default": False}), + "custom_width": ("INT", {"default": 2048, "min": 512, "max": 8192, "step": 64}), + "custom_height": ("INT", {"default": 2048, "min": 512, "max": 8192, "step": 64}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "edit" + CATEGORY = "image" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def edit(self, images, wavespeed_apikey, prompt, size="auto — match input (2K)", num_images=1, use_custom_size=False, custom_width=2048, custom_height=2048): + if wavespeed_apikey.strip(): + SeedreamEditAPINode._cached_api_key = wavespeed_apikey.strip() + api_key = wavespeed_apikey.strip() or SeedreamEditAPINode._cached_api_key + if not api_key: + raise RuntimeError("Seedream 4.5 Edit: WaveSpeed API key is required.") + if not prompt.strip(): + raise RuntimeError("Seedream 4.5 Edit: prompt is required.") + if images.shape[0] == 0: + raise RuntimeError("Seedream 4.5 Edit: at least one image is required.") + + # Resolve size + if use_custom_size: + api_size = f"{custom_width}*{custom_height}" + elif size.startswith("auto"): + # Use first image's exact aspect ratio, scale to meet minimum pixels + h, w = images.shape[1], images.shape[2] + min_pixels = 3686400 + # Scale up proportionally until we meet minimum pixels + scale = max(1.0, (min_pixels / (w * h)) ** 0.5) + new_w = int(round(w * scale / 64) * 64) + new_h = int(round(h * scale / 64) * 64) + # Clamp to API limits + new_w = max(512, min(8192, new_w)) + new_h = max(512, min(8192, new_h)) + api_size = f"{new_w}*{new_h}" + logging.info("Seedream auto size: input %dx%d -> output %s", w, h, api_size) + else: + api_size = size.split(" ")[0] # e.g. "2048*2048" from "2048*2048 — square_hd (1:1)" + + # Convert images to data URIs (max 10) + image_uris = [] + count = min(images.shape[0], 10) + for i in range(count): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype(np.uint8) + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + image_uris.append(f"data:image/png;base64,{b64}") + + payload = { + "images": image_uris, + "prompt": prompt, + "size": api_size, + "num_images": num_images, + "enable_sync_mode": True, + "enable_base64_output": True, + } + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + } + + try: + response = requests.post(self.BASE_URL, json=payload, headers=headers, timeout=180) + response.raise_for_status() + result = response.json() + except requests.exceptions.HTTPError as e: + raise RuntimeError(_api_error_msg("Seedream 4.5 Edit", e)) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"Seedream 4.5 Edit request error: {e!s}") + + data = result.get("data", {}) + + # Async polling fallback if sync mode didn't complete immediately + if data.get("status") not in ("completed",): + poll_url = data.get("urls", {}).get("get", "") + if not poll_url: + raise RuntimeError("Seedream 4.5 Edit: no poll URL and task not completed.") + for _ in range(90): + _time.sleep(2) + try: + poll_resp = requests.get(poll_url, headers=headers, timeout=30) + poll_resp.raise_for_status() + data = poll_resp.json().get("data", {}) + except requests.exceptions.RequestException as e: + logging.warning("Seedream 4.5 Edit poll error: %s", e) + continue + if data.get("status") == "completed": + break + if data.get("status") == "failed": + raise RuntimeError(f"Seedream 4.5 Edit failed: {data.get('error', 'unknown error')}") + else: + raise RuntimeError("Seedream 4.5 Edit timed out after 3 minutes.") + + outputs = data.get("outputs", []) + if not outputs: + raise RuntimeError("Seedream 4.5 Edit: no images in API response.") + + # Decode all output images + import torch + tensors = [] + for idx, output in enumerate(outputs): + if output.startswith("data:"): + b64_data = output.split(",", 1)[-1] + raw = base64.b64decode(b64_data) + elif output.startswith("http"): + try: + img_resp = requests.get(output, timeout=60) + img_resp.raise_for_status() + raw = img_resp.content + except requests.exceptions.RequestException as e: + raise RuntimeError(f"Seedream 4.5 Edit: failed to download image {idx}: {e!s}") + else: + # Assume raw base64 + raw = base64.b64decode(output) + tensor_tuple = _image_bytes_to_tensor(raw, "Seedream 4.5 Edit") + tensors.append(tensor_tuple[0]) + + if not tensors: + raise RuntimeError("Seedream 4.5 Edit: no valid images decoded.") + + batched = torch.cat(tensors, dim=0) + return (batched,) + + +# ---------- Seedream 4.5 Edit (fal.ai) ---------- + +_FAL_SEEDREAM_SIZES = [ + "auto — match input (2K)", + "1920*1920 — square (1:1)", + "2560*1920 — landscape (4:3)", + "1920*2560 — portrait (3:4)", + "1536*1920 — portrait (4:5)", + "1920*1536 — landscape (5:4)", + "2560*1440 — landscape (16:9)", + "1440*2560 — portrait (9:16)", +] + +_FAL_SIZE_MAP = { + "1920*1920": "square_hd", + "2560*1920": "landscape_4_3", + "1920*2560": "portrait_4_3", + "1536*1920": {"width": 1536, "height": 1920}, + "1920*1536": {"width": 1920, "height": 1536}, + "2560*1440": "landscape_16_9", + "1440*2560": "portrait_16_9", +} + + +class SeedreamEditFalAPINode: + """Edit images via ByteDance Seedream 4.5 Edit on fal.ai. + + Supports 1-10 reference images for context-aware editing with + facial feature, lighting, and color tone preservation up to 4K. + """ + + BASE_URL = "https://fal.run/fal-ai/bytedance/seedream/v4.5/edit" + _cached_api_key = "" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "fal_apikey": ("STRING", {"default": "", "multiline": False}), + "prompt": ("STRING", {"default": "", "multiline": True}), + }, + "optional": { + "size": (_FAL_SEEDREAM_SIZES, {"default": "auto — match input (2K)"}), + "num_images": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1}), + "use_custom_size": ("BOOLEAN", {"default": False}), + "custom_width": ("INT", {"default": 2048, "min": 512, "max": 8192, "step": 64}), + "custom_height": ("INT", {"default": 2048, "min": 512, "max": 8192, "step": 64}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = "edit" + CATEGORY = "image" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def edit(self, images, fal_apikey, prompt, size="auto — match input (2K)", num_images=1, use_custom_size=False, custom_width=2048, custom_height=2048): + if fal_apikey.strip(): + SeedreamEditFalAPINode._cached_api_key = fal_apikey.strip() + api_key = fal_apikey.strip() or SeedreamEditFalAPINode._cached_api_key + if not api_key: + raise RuntimeError("Seedream 4.5 Edit (fal.ai): fal.ai API key is required.") + if not prompt.strip(): + raise RuntimeError("Seedream 4.5 Edit (fal.ai): prompt is required.") + if images.shape[0] == 0: + raise RuntimeError("Seedream 4.5 Edit (fal.ai): at least one image is required.") + + # Resolve size + if use_custom_size: + fal_size = {"width": custom_width, "height": custom_height} + elif size.startswith("auto"): + # Use first image's exact aspect ratio, scale to ~2K + h, w = images.shape[1], images.shape[2] + target_pixels = 1920 * 1920 # 2K target + current_pixels = w * h + scale = (target_pixels / current_pixels) ** 0.5 + new_w = int(round(w * scale / 64) * 64) + new_h = int(round(h * scale / 64) * 64) + new_w = max(512, min(4096, new_w)) + new_h = max(512, min(4096, new_h)) + fal_size = {"width": new_w, "height": new_h} + logging.info("Seedream (fal.ai) auto size: input %dx%d -> output %dx%d", w, h, new_w, new_h) + else: + dimension_str = size.split(" ")[0] + fal_size = _FAL_SIZE_MAP.get(dimension_str, "square_hd") + + # Convert images to data URIs (max 10) + image_urls = [] + count = min(images.shape[0], 10) + for i in range(count): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype(np.uint8) + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + image_urls.append(f"data:image/png;base64,{b64}") + + payload = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_size, + "num_images": num_images, + "seed": _random.randint(0, 2147483647), + "enable_safety_checker": False, + } + headers = { + "Authorization": f"Key {api_key}", + "Content-Type": "application/json", + } + + try: + response = requests.post(self.BASE_URL, json=payload, headers=headers, timeout=180) + response.raise_for_status() + result = response.json() + except requests.exceptions.HTTPError as e: + raise RuntimeError(_api_error_msg("Seedream 4.5 Edit (fal.ai)", e)) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"Seedream 4.5 Edit (fal.ai) request error: {e!s}") + + fal_images = result.get("images", []) + if not fal_images: + raise RuntimeError("Seedream 4.5 Edit (fal.ai): no images in API response.") + + # Download and decode all result images + tensors = [] + for idx, fal_img in enumerate(fal_images): + img_url = fal_img.get("url", "") + if not img_url: + logging.warning("Seedream 4.5 Edit (fal.ai): no URL for image %d, skipping.", idx) + continue + try: + img_resp = requests.get(img_url, timeout=60) + img_resp.raise_for_status() + raw = img_resp.content + except requests.exceptions.RequestException as e: + raise RuntimeError(f"Seedream 4.5 Edit (fal.ai): failed to download image {idx}: {e!s}") + tensor_tuple = _image_bytes_to_tensor(raw, "Seedream 4.5 Edit (fal.ai)") + tensors.append(tensor_tuple[0]) + + if not tensors: + raise RuntimeError("Seedream 4.5 Edit (fal.ai): no valid images downloaded.") + + import torch + batched = torch.cat(tensors, dim=0) + return (batched,) + + +# ---------- Helpers ---------- + +def _images_to_parts(images): + """Convert ComfyUI IMAGE tensor [B, H, W, C] to list of inlineData parts.""" + parts = [] + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype(np.uint8) + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + parts.append({"inlineData": {"mimeType": "image/png", "data": b64}}) + return parts + + +def _apply_gemini_safety(payload, threshold): + """Apply safety threshold to all harm categories.""" + payload["safetySettings"] = [ + {"category": cat, "threshold": threshold} for cat in _HARM_CATEGORIES + ] + + +def _gemini_response_summary(data): + """Return a human-readable summary of why a Gemini response contained no image.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + prompt_feedback = data.get("promptFeedback", {}) + block_reason = prompt_feedback.get("blockReason", "") + if block_reason: + return f"Prompt was blocked: {block_reason}" + return "No candidates returned." + candidate = candidates[0] + finish_reason = candidate.get("finishReason", "") + parts = candidate.get("content", {}).get("parts") or [] + text_parts = [p["text"] for p in parts if "text" in p and not p.get("thought")] + if text_parts: + snippet = " | ".join(text_parts)[:300] + return f"Model returned text only (finishReason={finish_reason}): {snippet}" + return f"No image part in response (finishReason={finish_reason})." + except Exception: + return "" + + +def _extract_image_from_gemini_response(data, log_name): + """Extract the first non-thought inline image from a Gemini generateContent response.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + logging.warning("%s: response has no candidates. Full response: %s", log_name, data) + return None + candidate = candidates[0] + finish_reason = candidate.get("finishReason", "") + parts = candidate.get("content", {}).get("parts") or [] + logging.info("%s: finishReason=%s, part count=%d", log_name, finish_reason, len(parts)) + text_parts = [] + for part in parts: + if part.get("thought"): + continue + if "inlineData" in part: + b64 = part["inlineData"].get("data") + if b64: + return base64.b64decode(b64) + if "text" in part: + text_parts.append(part["text"]) + if text_parts: + logging.warning( + "%s: API returned text instead of image (finishReason=%s). Text: %s", + log_name, finish_reason, " | ".join(text_parts)[:500], + ) + else: + logging.warning( + "%s: no image or text in response. finishReason=%s. Full response: %s", + log_name, finish_reason, str(data)[:1000], + ) + except (KeyError, TypeError, ValueError) as e: + logging.warning("%s parse response: %s — raw: %s", log_name, e, str(data)[:500]) + return None + + +def _api_error_msg(service, e): + msg = f"{service} API HTTP error: {e.response.status_code}" + try: + body = e.response.json() + if "error" in body: + msg += f" — {body.get('error', body)}" + elif "message" in body: + msg += f" — {body.get('message', body)}" + except Exception: + text = e.response.text + if text: + msg += f" — {text[:200]}" + return msg + + +def _image_bytes_to_tensor(raw, log_name): + try: + image = Image.open(io.BytesIO(raw)).convert("RGB") + except Exception as e: + logging.error("%s: failed to decode image: %s", log_name, e) + raise RuntimeError(f"Failed to decode image from API: {e}") from e + arr = np.array(image).astype(np.float32) / 255.0 + tensor = torch.from_numpy(arr)[None, ...] + return (tensor,) + + +# ---------- ComfyUI registration ---------- + +NODE_CLASS_MAPPINGS = { + "NanoBananaProEditAPINode": NanoBananaProEditAPINode, + "NanoBanana2EditAPINode": NanoBanana2EditAPINode, + "SeedreamEditAPINode": SeedreamEditAPINode, + "SeedreamEditFalAPINode": SeedreamEditFalAPINode, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "NanoBananaProEditAPINode": "Aiorbust Nano Banana Pro Edit", + "NanoBanana2EditAPINode": "Aiorbust Nano Banana 2 Edit", + "SeedreamEditAPINode": "Aiorbust Seedream 4.5 Edit(Wavespeed)", + "SeedreamEditFalAPINode": "Aiorbust Seedream 4.5 Edit(fal.ai)", +} diff --git a/aiorbust-ofm-pack-main/README.md b/aiorbust-ofm-pack-main/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bad192e451be7adb8e6588bf628a340907e886d6 --- /dev/null +++ b/aiorbust-ofm-pack-main/README.md @@ -0,0 +1,89 @@ +# aiorbust OFM ComfyUI Nodes (Monthly) + +Custom ComfyUI nodes for AI-powered image editing and prompt management. + +## Nodes + +### Nano Banana Pro Edit + +Edit and transform images using Google's Gemini 3 Pro model through a simple API call. Supports custom aspect ratios, resolution up to 4K, and adjustable safety filters. + +**Inputs:** + +| Input | Type | Default | Description | +|---|---|---|---| +| images | IMAGE | — | Input image(s) to edit | +| api_key | String | — | Your Google Gemini API key | +| prompt | Multiline String | — | Instructions for how to edit the image | +| aspect_ratio | Dropdown | `auto` | Output aspect ratio: auto, 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 | +| image_size | Dropdown | `2K` | Output resolution: 1K, 2K, or 4K | +| temperature | Float (0–2) | 1.0 | Controls creativity — higher = more creative | +| safety_threshold | Dropdown | `BLOCK_ONLY_HIGH` | Content safety filter level | + +**Output:** `IMAGE` tensor + +--- + +### Nano Banana 2 Edit + +A faster, lighter image editor powered by Gemini 3.1 Flash for quick image edits and modifications. Same flexible controls as Pro but optimized for speed. + +**Inputs:** + +| Input | Type | Default | Description | +|---|---|---|---| +| images | IMAGE | — | Input image(s) to edit | +| api_key | String | — | Your Google Gemini API key | +| prompt | Multiline String | — | Instructions for how to edit the image | +| aspect_ratio | Dropdown | `auto` | Output aspect ratio | +| image_size | Dropdown | `1K` | Output resolution: 1K, 2K, or 4K | +| temperature | Float (0–2) | 1.0 | Controls creativity | +| safety_threshold | Dropdown | `BLOCK_ONLY_HIGH` | Content safety filter level | + +**Output:** `IMAGE` tensor + +--- + +### Example Prompt Selector + +Browse and select from pre-written example prompts stored in text files. Outputs the selected prompt as a STRING to connect to other nodes. + +**Inputs:** + +| Input | Type | Description | +|---|---|---| +| prompt_file | Dropdown | Select which `.txt` file to browse prompts from | +| example_prompt | Dropdown | Browse prompts from the selected file | +| prompt_text | Multiline String | Editable text area — auto-populated when you select a prompt. Edit to customize. | + +**Output:** `STRING` — the prompt text. Uses `prompt_text` if manually edited, otherwise the selected example prompt. + +**Navigation:** Use the `Prev Prompt` / `Next Prompt` buttons to cycle through prompts, or click the dropdown to pick directly. + +#### Adding Your Own Prompts + +1. Create a `.txt` file in the `prompts/` folder (e.g., `prompts/my_styles.txt`) +2. Write one prompt per block, separated by `---` on its own line: + +``` +A beautiful sunset over the ocean, golden light, dramatic clouds +--- +A cyberpunk street scene at night, neon reflections, rain-soaked pavement +--- +A cozy cabin interior with fireplace, warm lighting, rustic furniture +``` + +3. Restart ComfyUI — the new file appears in the `prompt_file` dropdown + +## File Structure + +``` +aiorbust-OFM-pack-Monthly/ +├── __init__.py # Node registration +├── Node.py # NanoBananaProEditAPINode, NanoBanana2EditAPINode +├── prompt_selector.py # PromptSelectorNode + API routes +├── js/ +│ └── prompt_selector.js # Frontend: prompt navigation + text population +└── prompts/ + └── *.txt # Prompt files (--- separated) +``` diff --git a/aiorbust-ofm-pack-main/Tattoos/02e55877541b2abc009c40857bb81f7c.jpg b/aiorbust-ofm-pack-main/Tattoos/02e55877541b2abc009c40857bb81f7c.jpg new file mode 100644 index 0000000000000000000000000000000000000000..184fb9bce8ffc887936f0cb8b3e562381f38735a Binary files /dev/null and b/aiorbust-ofm-pack-main/Tattoos/02e55877541b2abc009c40857bb81f7c.jpg differ diff --git a/aiorbust-ofm-pack-main/Tattoos/379aa9dc1fc4cb71d0abcf9e41031df6.jpg b/aiorbust-ofm-pack-main/Tattoos/379aa9dc1fc4cb71d0abcf9e41031df6.jpg new file mode 100644 index 0000000000000000000000000000000000000000..61d2f63445cc6503def0e352906a5e9e76a54352 Binary files /dev/null and b/aiorbust-ofm-pack-main/Tattoos/379aa9dc1fc4cb71d0abcf9e41031df6.jpg differ diff --git a/aiorbust-ofm-pack-main/Tattoos/38cb0b53461bc5072be6fd4601ab9086.jpg b/aiorbust-ofm-pack-main/Tattoos/38cb0b53461bc5072be6fd4601ab9086.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3b7012b17862d51e8efef4b1eac99370b6484927 Binary files /dev/null and b/aiorbust-ofm-pack-main/Tattoos/38cb0b53461bc5072be6fd4601ab9086.jpg differ diff --git a/aiorbust-ofm-pack-main/Tattoos/49f2fc0dbff9bc228392b680db029b27.jpg b/aiorbust-ofm-pack-main/Tattoos/49f2fc0dbff9bc228392b680db029b27.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b906243f69fa1077434e65633673a364d1058fca --- /dev/null +++ b/aiorbust-ofm-pack-main/Tattoos/49f2fc0dbff9bc228392b680db029b27.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1eac76048cda920f22390d72822d7fee93d2bb37fbf417bdee6a67900338836d +size 182360 diff --git a/aiorbust-ofm-pack-main/Tattoos/5c92d43a5b8eb4846805f182125fbbe4.jpg b/aiorbust-ofm-pack-main/Tattoos/5c92d43a5b8eb4846805f182125fbbe4.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a3fbbee5511769a21b5aafa130796dba3728bcaf Binary files /dev/null and b/aiorbust-ofm-pack-main/Tattoos/5c92d43a5b8eb4846805f182125fbbe4.jpg differ diff --git a/aiorbust-ofm-pack-main/Tattoos/5d8eafa003576838106a0c4bf08c7052.jpg b/aiorbust-ofm-pack-main/Tattoos/5d8eafa003576838106a0c4bf08c7052.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5c9acdebc0558d44df67d0ec5315aa8ca0ee2bf7 --- /dev/null +++ b/aiorbust-ofm-pack-main/Tattoos/5d8eafa003576838106a0c4bf08c7052.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41f3d478b7fad47d9c28ba5df3ee6f757aca00e7b6afb8281d4a32bfebce0cfd +size 167076 diff --git a/aiorbust-ofm-pack-main/Tattoos/b3e14391b8dcd3e7cb05170e74b0aa40.jpg b/aiorbust-ofm-pack-main/Tattoos/b3e14391b8dcd3e7cb05170e74b0aa40.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7a2af723a3a07b2080573b8854cb0c4c478be0c8 Binary files /dev/null and b/aiorbust-ofm-pack-main/Tattoos/b3e14391b8dcd3e7cb05170e74b0aa40.jpg differ diff --git a/aiorbust-ofm-pack-main/Tattoos/c49ad34d13d02490080ff127415ad620.jpg b/aiorbust-ofm-pack-main/Tattoos/c49ad34d13d02490080ff127415ad620.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0f517ff39469f50a8abe2c439c1e4546087a20c4 Binary files /dev/null and b/aiorbust-ofm-pack-main/Tattoos/c49ad34d13d02490080ff127415ad620.jpg differ diff --git a/aiorbust-ofm-pack-main/Tattoos/f120ecf21ddd9a05bde3a44757a93070.jpg b/aiorbust-ofm-pack-main/Tattoos/f120ecf21ddd9a05bde3a44757a93070.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b40e439d98a6f582b56c64069b31f32635c09167 Binary files /dev/null and b/aiorbust-ofm-pack-main/Tattoos/f120ecf21ddd9a05bde3a44757a93070.jpg differ diff --git a/aiorbust-ofm-pack-main/__init__.py b/aiorbust-ofm-pack-main/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5108d379d642c0283896617e5e70dae17b588db6 --- /dev/null +++ b/aiorbust-ofm-pack-main/__init__.py @@ -0,0 +1,88 @@ +"""ComfyUI custom nodes for Nano Banana Pro and Nano Banana 2 APIs (Monthly).""" +from .Node import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS +from .gemini_prompt import GeminiPromptNode +from .prompt_selector import PromptSelectorNode +from .directory_loader import DirectoryImageLoaderNode +from .api_keys import LoadAPIKeysNode +from .video_frame_extractor import VideoFrameExtractorNode +from .image_processing import MetadataRemoveNode, SaveAsPhonePhotoNode +from .lora_caption import LoraCaptionGeneratorNode +from .nodes.nano_banana_aio import NanoBananaAIO +from .nodes.imageUtils import PreviewImageWithoutMetadata +from .nodes.aiorbust_video_loader import AiorBustVideoLoader +from .nodes.instagram_faceswap import InstagramFaceSwapNode +from .nodes.dataset_creator import DatasetCreatorNode + +# Post-processing nodes (dossier avec espace + noms unicode -> importlib) +import importlib.util as _ilu, os as _os + +_pack_root = _os.path.dirname(_os.path.abspath(__file__)) + +def _load_pp(filename, modname): + _path = _os.path.join(_pack_root, "post processing", filename) + _spec = _ilu.spec_from_file_location(modname, _path) + _mod = _ilu.module_from_spec(_spec) + _spec.loader.exec_module(_mod) + return _mod + +try: + _renoise_mod = _load_pp("Aiorbust_Renoïse.py", "Aiorbust_Renoise_mod") + Aiorbust_Renoise = _renoise_mod.Aiorbust_Renoise + print("[Aiorbust] ✅ Renoïse chargé") +except Exception as _e: + Aiorbust_Renoise = None + print(f"[Aiorbust] ❌ Renoïse failed: {_e}") + +try: + _camera_look_mod = _load_pp("Aiorbust_camera_look.py", "Aiorbust_Camera_Look_mod") + Aiorbust_Camera_Look = _camera_look_mod.Aiorbust_Camera_Look + print("[Aiorbust] ✅ Camera Look chargé") +except Exception as _e: + Aiorbust_Camera_Look = None + print(f"[Aiorbust] ❌ Camera Look failed: {_e}") + +try: + _apply_lut_mod = _load_pp("Aiorbust_Apply_LUT.py", "Aiorbust_Apply_LUT_mod") + Aiorbust_Apply_LUT = _apply_lut_mod.Aiorbust_Apply_LUT + print("[Aiorbust] ✅ Apply LUT chargé") +except Exception as _e: + Aiorbust_Apply_LUT = None + print(f"[Aiorbust] ❌ Apply LUT failed: {_e}") + +WEB_DIRECTORY = "./js" + +NODE_CLASS_MAPPINGS["NanoBananaAIO"] = NanoBananaAIO +NODE_CLASS_MAPPINGS["GeminiPromptNode"] = GeminiPromptNode +NODE_CLASS_MAPPINGS["PromptSelectorNodeMonthly"] = PromptSelectorNode +NODE_CLASS_MAPPINGS["DirectoryImageLoaderNode"] = DirectoryImageLoaderNode +NODE_CLASS_MAPPINGS["LoadAPIKeysNode"] = LoadAPIKeysNode +NODE_CLASS_MAPPINGS["VideoFrameExtractorNode"] = VideoFrameExtractorNode +NODE_CLASS_MAPPINGS["MetadataRemoveNodeMonthly"] = MetadataRemoveNode +NODE_CLASS_MAPPINGS["SaveAsPhonePhotoNodeMonthly"] = SaveAsPhonePhotoNode +NODE_CLASS_MAPPINGS["LoraCaptionGeneratorNode"] = LoraCaptionGeneratorNode +NODE_CLASS_MAPPINGS["PreviewImageWithoutMetadata"] = PreviewImageWithoutMetadata +NODE_CLASS_MAPPINGS["AiorBustVideoLoader"] = AiorBustVideoLoader +NODE_CLASS_MAPPINGS["InstagramFaceSwapNode"] = InstagramFaceSwapNode +NODE_CLASS_MAPPINGS["DatasetCreatorNode"] = DatasetCreatorNode +if Aiorbust_Renoise: NODE_CLASS_MAPPINGS["Aiorbust_Renoise"] = Aiorbust_Renoise +if Aiorbust_Camera_Look: NODE_CLASS_MAPPINGS["Aiorbust_Camera_Look"] = Aiorbust_Camera_Look +if Aiorbust_Apply_LUT: NODE_CLASS_MAPPINGS["Aiorbust_Apply_LUT"] = Aiorbust_Apply_LUT + +NODE_DISPLAY_NAME_MAPPINGS["NanoBananaAIO"] = "Aiorbust Image and Video Edit AIO" +NODE_DISPLAY_NAME_MAPPINGS["GeminiPromptNode"] = "Aiorbust Prompt Generator" +NODE_DISPLAY_NAME_MAPPINGS["PromptSelectorNodeMonthly"] = "Aiorbust Prompt Selector" +NODE_DISPLAY_NAME_MAPPINGS["DirectoryImageLoaderNode"] = "Aiorbust Directory Image Loader" +NODE_DISPLAY_NAME_MAPPINGS["LoadAPIKeysNode"] = "Aiorbust Load API Keys" +NODE_DISPLAY_NAME_MAPPINGS["VideoFrameExtractorNode"] = "Aiorbust Video Frame Extractor" +NODE_DISPLAY_NAME_MAPPINGS["MetadataRemoveNodeMonthly"] = "Aiorbust Remove Image Metadata" +NODE_DISPLAY_NAME_MAPPINGS["SaveAsPhonePhotoNodeMonthly"] = "Aiorbust Save as Phone Photo" +NODE_DISPLAY_NAME_MAPPINGS["LoraCaptionGeneratorNode"] = "Aiorbust Lora Caption Generator" +NODE_DISPLAY_NAME_MAPPINGS["PreviewImageWithoutMetadata"] = "Aiorbust Preview No Metadata" +NODE_DISPLAY_NAME_MAPPINGS["AiorBustVideoLoader"] = "Aiorbust Video Loader" +NODE_DISPLAY_NAME_MAPPINGS["InstagramFaceSwapNode"] = "Aiorbust Content Remaker" +NODE_DISPLAY_NAME_MAPPINGS["DatasetCreatorNode"] = "Aiorbust Dataset Creator" +NODE_DISPLAY_NAME_MAPPINGS["Aiorbust_Renoise"] = "Aiorbust Renoise" +NODE_DISPLAY_NAME_MAPPINGS["Aiorbust_Camera_Look"] = "📷 Aiorbust Camera Look" +NODE_DISPLAY_NAME_MAPPINGS["Aiorbust_Apply_LUT"] = "🎨 Aiorbust Apply LUT" + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] diff --git a/aiorbust-ofm-pack-main/_backups/20260424_212126_gemini_prompt.py b/aiorbust-ofm-pack-main/_backups/20260424_212126_gemini_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..ad8b3044b7e6cf276651b0cb03dae2a74ee465b7 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260424_212126_gemini_prompt.py @@ -0,0 +1,942 @@ +""" +ComfyUI node — OFM Prompt Generator. +Uses Gemini LLM to analyze images and generate structured JSON prompts, +or allows custom freeform prompt generation. +""" + +import io +import base64 +import logging +import re +import os +import sys +import json +import subprocess + +import numpy as np +import requests +from PIL import Image + + + +_PROVIDERS = ["Gemini", "Grok", "Vertex"] + +_GEMINI_MODELS = [ + "gemini-2.5-pro", + "gemini-2.5-flash", + "gemini-2.0-flash", +] + +_GROK_MODELS = [ + # Vision-capable models (support image input) + "grok-4.20-0309-reasoning", + "grok-4.20-0309-non-reasoning", + "grok-4-1-fast-reasoning", + "grok-4-1-fast-non-reasoning", + "grok-2-vision-1212", + # Text-only models (no image input) + "grok-3", + "grok-3-fast", + "grok-3-mini", + "grok-3-mini-fast", +] + +_PROMPT_MODES = [ + "JSON Image Analysis", + "Style Transfer Prompt", + "Seedream Edit (2 face + 1 ref)", + "Seedream Edit (1 face + 1 ref)", + "Seedream Edit (2 face and body + 1 ref)", + "Seedream Edit (2 faces + 2 bodies + 1ref)", + "Custom Prompt", +] + +# ---------- Built-in JSON analysis prompt ---------- + +_JSON_ANALYSIS_PROMPT = r"""## Context & Goal +You are an expert visual analysis specialist with 15+ years of experience in digital art, photography, graphic design, and AI image generation. You excel at deconstructing visual elements and translating artistic styles into technical specifications. + +Your task: Analyze the uploaded image and return a comprehensive JSON profile for recreating the visual style. + +## Output Format +Return ONLY valid JSON. No explanations, no commentary, no markdown formatting. + +## Core JSON Schema + +{ +"metadata": { +"confidence_score": "high/medium/low - assessment of analysis accuracy", +"image_type": "photograph/digital art/illustration/graphic design/mixed media", +"primary_purpose": "marketing/editorial/social media/product/portrait/landscape/abstract" +}, +"composition": { +"rule_applied": "rule of thirds/golden ratio/center composition/symmetry/asymmetry", +"aspect_ratio": "width:height ratio or format description", +"layout": "grid/single subject/multi-element/layered", +"focal_points": [ +"Primary focal point location and element", +"Secondary focal point if present" +], +"visual_hierarchy": "Description of how eye moves through the image", +"balance": "symmetric/asymmetric/radial - with description" +}, +"color_profile": { +"dominant_colors": [ +{ +"color": "Specific color name", +"hex": "#000000", +"percentage": "approximate percentage of image", +"role": "background/accent/primary subject" +} +], +"color_palette": "complementary/analogous/triadic/monochromatic/split-complementary", +"temperature": "warm/cool/neutral - overall feeling", +"saturation": "highly saturated/moderate/desaturated/black and white", +"contrast": "high contrast/medium contrast/low contrast/soft" +}, +"lighting": { +"type": "natural window/artificial/mixed/studio/practical lights", +"source_count": "single source/multiple sources - number and placement", +"direction": "front/45-degree side/90-degree side/back/top/bottom/diffused from above", +"directionality": "highly directional/moderately directional/diffused/omni-directional", +"quality": "hard light/soft light/dramatic/even/gradient/sculpted", +"intensity": "bright/moderate/low/moody/high-key/low-key", +"contrast_ratio": "high contrast (dramatic shadows)/medium contrast/low contrast (flat)", +"mood": "cheerful/dramatic/mysterious/calm/energetic/professional/casual", +"shadows": { +"type": "harsh defined edges/soft gradual edges/minimal/dramatic/absent", +"density": "deep black/gray/transparent/faint", +"placement": "under subject/on wall/from objects/cast patterns", +"length": "short/medium/long - shadow projection distance" +}, +"highlights": { +"treatment": "blown out/preserved/subtle/dramatic/specular", +"placement": "on face/hair/clothing/background - where light hits strongest" +}, +"ambient_fill": "present/absent - secondary fill light reducing shadows", +"light_temperature": "warm (golden)/neutral/cool (blue) - color cast" +}, +"technical_specs": { +"medium": "digital photography/3D render/digital painting/vector/photo manipulation/mixed", +"style": "realistic/hyperrealistic/stylized/minimalist/maximalist/abstract/surreal", +"texture": "smooth/grainy/sharp/soft/painterly/glossy/matte", +"sharpness": "tack sharp/slightly soft/deliberately soft/bokeh effect", +"grain": "none/film grain/digital noise/intentional grain - level", +"depth_of_field": "shallow/medium/deep - with subject isolation description", +"perspective": "straight on/low angle/high angle/dutch angle/isometric/one-point/two-point" +}, +"artistic_elements": { +"genre": "portrait/landscape/abstract/conceptual/commercial/editorial/street/fine art", +"influences": [ +"Identified artistic movement, photographer, or style influence" +], +"mood": "energetic/calm/dramatic/playful/sophisticated/raw/polished", +"atmosphere": "Description of overall feeling and emotional impact", +"visual_style": "clean/cluttered/minimal/busy/organic/geometric/fluid/structured" +}, +"typography": { +"present": "true or false", +"fonts": [ +{ +"type": "sans-serif/serif/script/display/handwritten", +"weight": "thin/light/regular/medium/bold/black", +"characteristics": "modern/vintage/playful/serious/technical" +} +], +"placement": "overlay/integrated/border/corner - with strategic description", +"integration": "subtle/prominent/dominant/background" +}, +"subject_analysis": { +"primary_subject": "Main subject description - DO NOT describe face structure, hair, skin tone, or any identity features", +"positioning": "center/left/right/top/bottom/rule of thirds placement", +"scale": "close-up/medium/full/environmental/macro", +"interaction": "isolated/interacting with environment/multiple subjects", +"facial_expression": { +"mouth": "closed smile/open smile/slight smile/neutral/serious/pursed - exact mouth position", +"smile_intensity": "no smile/subtle/moderate/broad/wide - degree of smile", +"eyes": "direct gaze/looking away/squinting/wide/relaxed/intense - eye expression", +"eyebrows": "raised/neutral/furrowed/relaxed - brow position", +"overall_emotion": "happy/content/serious/playful/confident/approachable/guarded/warm/cold", +"authenticity": "genuine/posed/candid/formal/natural" +}, +"hands_and_gestures": { +"left_hand": "Exact position and gesture - touching face/holding object/resting on surface/in pocket/behind back/clasped/visible or not visible", +"right_hand": "Exact position and gesture - touching face/holding object/resting on surface/in pocket/behind back/clasped/visible or not visible", +"finger_positions": "Specific details: pointing/peace sign/thumbs up/relaxed/gripping/spread/interlaced/curled", +"finger_interlacing": "if hands clasped: natural loose interlacing/tight formal interlacing/fingers overlapping/thumbs position", +"hand_tension": "relaxed/tense/natural/posed/rigid - muscle tension observable", +"interaction": "What hands are doing: holding phone/touching hair/on hip/crossed/clasped at waist/clasped at chest/gesturing", +"naturalness": "organic casual gesture/deliberately posed/caught mid-motion/static formal pose" +}, +"body_positioning": { +"posture": "standing/sitting/leaning/lying - exact position", +"angle": "facing camera/45 degree turn/profile/back to camera", +"weight_distribution": "leaning left/right/centered/shifted", +"shoulders": "level/tilted/rotated/hunched/back" +} +}, +"background": { +"setting_type": "indoor/outdoor/studio/natural environment - specific location", +"spatial_depth": "shallow/medium/deep - layers description", +"elements_detailed": [ +{ +"item": "Specific object name (if plant: species like monstera/pothos/bird of paradise/fern)", +"position": "left/right/center/top/bottom - exact placement with quadrant", +"distance": "foreground/midground/background", +"size": "dominant/medium/small - relative scale and proportion", +"condition": "new/worn/vintage/pristine/wilted/thriving - state description", +"specific_features": "For plants: flower color, leaf pattern, pot type; For objects: brand, wear, details" +} +], +"wall_surface": { +"material": "painted drywall/concrete/brick/wood paneling/tile/wallpaper/plaster - exact base material", +"surface_treatment": "smooth paint/textured paint/raw concrete/polished concrete/exposed brick/finished/unfinished", +"texture": "perfectly smooth/slightly textured/rough/patterned/brushed - tactile quality", +"finish": "matte/satin/glossy/flat - sheen level", +"color": "Specific color with undertones (e.g., warm gray, cool blue-gray, off-white)", +"color_variation": "uniform/gradient/patchy/streaked - color consistency", +"features": "clean/water stains/vertical streaks/horizontal marks/cracks/patches/fixtures/artwork/scuffs - ALL observable surface details", +"wear_indicators": "pristine/aged/weathered/industrial/residential - condition and style" +}, +"floor_surface": { +"material": "wood/tile/carpet/concrete/grass - exact type", +"color": "Specific color", +"pattern": "solid/checkered/striped/herringbone - if present" +}, +"objects_catalog": "List every visible object with position: furniture pieces, decorative items, functional objects, natural elements", +"background_treatment": "blurred/sharp/minimal/detailed/gradient/textured" +}, +"generation_parameters": { +"prompts": [ +"Detailed technical prompt for recreating this style", +"Alternative angle or variation prompt" +], +"keywords": [ +"keyword1", +"keyword2", +"keyword3", +"keyword4", +"keyword5" +], +"technical_settings": "Recommended camera/render settings description for recreation", +"post_processing": "Color grading, filters, or editing techniques applied" +} +} + +## Analysis Rules + +### Composition Analysis +- Identify grid systems, alignment, and spatial relationships +- Note use of negative space and breathing room +- Describe visual flow and eye movement path +- Identify focal points using color, contrast, size, or placement +- Assess balance between elements + +### Color Analysis +- Extract dominant colors with approximate hex values +- Identify color relationships (complementary, analogous, etc.) +- Assess temperature bias (warm vs cool) +- Note saturation levels and contrast intensity +- Describe how color creates mood and directs attention + +### Lighting Assessment +- Determine light source type, direction, and quality +- Analyze shadow characteristics and depth +- Assess highlight preservation or blown-out areas +- Describe overall lighting mood and emotional impact +- Note light's role in creating dimension and form + +### Technical Evaluation +- Identify creation medium and technique +- Assess texture, sharpness, and grain characteristics +- Evaluate depth of field and focus points +- Analyze perspective and viewpoint +- Note any technical limitations or intentional choices + +### Artistic Context +- Identify genre and artistic influences +- Assess mood, atmosphere, and emotional tone +- Describe visual style (minimal, maximalist, etc.) +- Note any cultural or temporal references +- Evaluate overall aesthetic cohesion + +### Typography (if present) +- Identify font styles and weights +- Assess placement and integration strategy +- Evaluate readability and hierarchy +- Describe relationship to other visual elements + +### Subject Treatment +- **CRITICAL EXCLUSION — Face & Hair**: Do NOT describe facial features, facial expression, hair color, hair style, hair length, hair texture, skin tone, eye color, or any identity-defining features. These will be provided by separate face reference images. Skip these entirely. +- **Hand & Gesture Analysis (CRITICAL)**: + - Describe EACH hand separately with exact position + - Note if hands are visible or hidden (in pockets, behind back, out of frame) + - Document specific finger positions and shapes + - For clasped hands: describe interlacing style (natural loose vs formal tight), thumb positions, finger overlap patterns + - Assess hand tension: relaxed vs tense, organic vs posed + - Describe what hands are interacting with (phone, face, object, clothing, each other) + - Note natural vs posed quality of gesture + - Specify pressure/contact points (lightly touching vs gripping) + - Evaluate overall naturalness: organic casual vs deliberately posed +- **Background Elements (CRITICAL)**: + - Catalog EVERY visible object with exact position and quadrant placement + - For plants: identify species (monstera, pothos, bird of paradise, fern, etc.) + - Describe spatial relationships between objects and their depth layers + - **Wall analysis is CRITICAL**: + - Distinguish between painted drywall vs concrete vs brick vs other materials + - Note surface treatment: smooth paint vs textured vs raw vs polished + - Document finish: matte vs glossy vs satin + - Identify any surface features: water stains, streaks, cracks, patches, wear + - Assess condition: pristine residential vs industrial weathered vs aged + - Document floor type, color, pattern + - Specify distance/depth layer for each element + - Note condition and state of objects (new/worn/vintage/thriving/wilted) + - Describe any text, artwork, or decorative elements + - Include architectural features (windows, doors, molding, fixtures, frames) +- **Lighting Analysis (CRITICAL)**: + - Distinguish between dramatic directional lighting vs flat even lighting + - Assess directionality: highly directional (strong shadows) vs diffused (soft minimal shadows) + - Document shadow characteristics: harsh defined edges vs soft gradual edges vs minimal + - Note contrast ratio: high contrast (dramatic) vs low contrast (flat) + - Identify if ambient fill light is present reducing shadow depth + - Describe how light sculpts the subject vs evenly illuminates + - Document cast shadows from objects (like plants) on walls + - Note shadow density: deep black vs gray vs faint +- Analyze primary subject and positioning (but NOT face, hair, or identity features) +- Assess scale and framing choices +- Describe subject-background relationship +- Note any secondary subjects or supporting elements + +### Generation Parameters +- Create actionable technical prompts for recreation +- Extract relevant keywords for searchability +- Recommend technical settings for similar results +- Describe post-processing techniques applied + +## Output Requirements +- **Format**: Valid JSON only +- **No markdown**: No ```json``` blocks, no backticks +- **No commentary**: No explanatory text before/after JSON +- **No instructions**: No "Here is your analysis" or "Copy this" +- **Clean structure**: Properly formatted, parseable JSON +- **Single object**: Return one complete JSON analysis object +- **Comprehensive**: All sections must be populated with detailed analysis +- **Specific**: Use precise technical terminology, not vague descriptions +- **Actionable**: Generation parameters must be detailed enough for recreation + +## Processing Logic +1. Analyze the provided image comprehensively across all categories +2. Extract technical specifications and artistic elements +3. Generate recreation prompts and parameters +4. Output single, complete JSON object + +## Quality Standards +- **Confidence score**: Honest assessment of analysis certainty +- **Hex codes**: Approximate but reasonable color values +- **Specific descriptions**: Avoid generic terms like "nice" or "good" +- **Technical accuracy**: Use correct terminology for medium and technique +- **Completeness**: Every JSON field must contain meaningful analysis +- **Actionability**: Prompts and keywords must be specific enough to recreate style + +### CRITICAL Accuracy Requirements: + +**CRITICAL EXCLUSION — Face Structure & Hair:** +- Do NOT include any hair fields (length, cut, texture, styling, part, volume, details, color) +- Do NOT describe face structure, skin tone, eye color, hair color, or any identity-defining features +- These are controlled by separate face reference images and must be omitted entirely +- EXCEPTION: DO include facial_expression fields (mouth position, smile intensity, eye gaze, eyebrow position, emotion, authenticity) — expressions must be captured from the analyzed image + +**Hand & Gesture Description Must Include:** +- Position of BOTH hands (even if one is hidden) +- Exact finger configurations +- For clasped hands: interlacing pattern (loose/tight), thumb position, finger overlap +- Hand tension assessment (relaxed vs tense) +- What hands are interacting with +- Natural vs posed quality with specific evidence +- Contact points and pressure +- Overall gesture naturalness assessment + +**Background Description Must Include:** +- Every visible object cataloged with quadrant position +- Plant species identification (not just "plant") +- Wall material distinction (painted drywall vs concrete vs brick - THIS IS CRITICAL) +- Wall surface treatment (smooth paint vs raw concrete vs textured) +- Wall finish (matte vs glossy) and condition (pristine vs weathered vs industrial) +- Any surface features: water stains, vertical streaks, cracks, patches +- Floor materials with exact colors +- Spatial depth layers (foreground/mid/background) for each element +- Object conditions and states +- Architectural features +- Text or decorative elements + +**Lighting Description Must Include:** +- Directionality assessment (highly directional vs diffused) +- Contrast ratio (high/medium/low) +- Shadow characteristics: edge quality (harsh vs soft), density (deep vs faint), placement +- Cast shadows from objects onto walls +- Presence or absence of ambient fill light +- Whether lighting is dramatic and sculpting vs flat and even +- This distinction is CRITICAL for recreation accuracy + +**Facial Expression (INCLUDE — this is the exception):** +- Exact mouth position (closed smile/slight smile/neutral/serious) +- Smile intensity quantification +- Eye gaze direction and expression +- Eyebrow position +- Overall emotional tone (warm vs neutral vs serious) +- Genuine vs posed quality assessment +- NOTE: Describe the EXPRESSION only, NOT the facial structure (no face shape, no eye color, no skin tone)""" + + +# ---------- Built-in style transfer prompt ---------- + +_STYLE_TRANSFER_PROMPT = r"""You are an expert image editing prompt engineer. Analyze this reference image and extract ALL visual characteristics that should be transferred to another image. Then generate a concise, actionable editing instruction. + +Extract and describe these elements: + +**Subject Appearance:** +- **Clothing**: exact garments, colors, fabrics, fit, style (e.g., "oversized cream knit sweater with a V-neck", "black leather jacket unzipped over a white graphic tee") +- **Pose**: exact body position, angle, weight distribution, hand placement, arm positions, lean direction +- **Facial expression**: exact mouth position (smile type/intensity), eye gaze direction, eyebrow position, overall emotional tone +- **Hair styling**: current style, part, volume, texture state + +**Visual Style:** +- **Lighting**: direction, quality (hard/soft), intensity, color temperature, shadow characteristics +- **Color grading**: overall palette, temperature, saturation, contrast, any color tint or cast +- **Mood/atmosphere**: emotional tone, ambiance +- **Texture/grain**: film grain, noise, smoothness, sharpness +- **Depth of field**: bokeh style, focus +- **Post-processing**: filters, vignetting, bloom, haze, matte look +- **Background**: setting type, colors, blur level, key elements + +Output ONLY the editing instruction as a single paragraph. No explanations, no bullet points, no headers, no markdown. + +Format your output exactly like this example: +"Edit this image so the subject is wearing an oversized cream knit sweater with a V-neck, posed leaning slightly against a wall with their left hand in their pocket and right hand touching their hair, with a relaxed genuine slight smile and direct eye contact, warm golden hour lighting from the left side with soft diffused shadows, desaturated film look with lifted blacks and muted earth tones, subtle film grain, shallow depth of field with a blurred neutral-toned indoor background." + +Be extremely specific about clothing, pose, and expression. The output will be fed directly to an AI image editing model.""" + + +# ---------- Built-in Seedream Edit prompt ---------- + +_SEEDREAM_EDIT_PROMPT = r"""You are Gemini 2.5, an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. +Primary Directive: Your task is to analyze Reference Image 3 (a complete scene) and generate a single, comprehensive prompt for Seedream 4.5. This prompt will instruct the model on how to use a total of three reference images. +Critical Context (Non-negotiable): Seedream will always receive 3 reference images in this specific order: +Images 1 & 2: Provide the subject's complete face structure, facial features, and identity. +Image 3: The complete scene reference (this is the image you will be given to analyze). +Your analysis must focus exclusively on Image 3. Your generated prompt must correctly instruct Seedream on this specific 3-image workflow. +Your Generation Task: +You will be given Image 3. +You will analyze Image 3 ONLY. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. +Mandatory Output Format (Strict Template): +Use the first two reference images for the subject's complete face, features, and identity. Use reference image 3 as the complete reference for all other elements: clothing, pose, action, body type, scene composition, background environment, lighting, and overall atmosphere. +Subject details: [Describe the subject's clothing in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the features.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +_SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT = r"""You are an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. + +Primary Directive: Your task is to analyze all 3 provided images and generate a single, comprehensive prompt for Seedream 4.5. + +Critical Context (Non-negotiable): Seedream will always receive 3 reference images in this specific order: +Images 1 & 2: Provide the subject's complete face structure, facial features, identity, AND body type, body shape, body proportions, skin tone, and any body-specific details such as tattoos, scars, or markings. The output body MUST match these images. +Image 3: The complete scene reference. Provides ONLY the clothing, pose, action, scene composition, background environment, lighting, and overall atmosphere. The body type in Image 3 should be IGNORED — the body must come from Images 1 & 2. + +Your Generation Task: +You will be given all 3 images. +You will analyze Images 1 & 2 for the subject's body proportions and physical build. +You will analyze Image 3 for the scene, clothing, pose, lighting, and atmosphere. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. + +Mandatory Output Format (Strict Template): +Use the first two reference images for the subject's complete face, features, identity, body type, body shape, proportions, skin tone, and any body-specific details such as tattoos or markings. Use reference image 3 as the reference for clothing, pose, action, scene composition, background environment, lighting, and overall atmosphere ONLY — do NOT use image 3 for body type or physique. +Body proportions (from images 1 & 2): [Describe the subject's body proportions in explicit detail as observed in images 1 & 2. Include: overall build (e.g., slim, athletic, curvy, petite, voluptuous), bust/chest size (e.g., small, medium, large, very large), waist (e.g., narrow, thin, wide), hip and butt size (e.g., small, round, wide, large), leg shape (e.g., long, toned, thick), shoulder width, and any other distinctive body features. Be specific and direct — these proportions MUST be preserved in the output regardless of what Image 3's body looks like.] +Subject details: [Describe the subject's clothing from Image 3 in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose from Image 3: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the facial features.] [The body wearing these clothes must match images 1 & 2's body proportions exactly. Any tattoos, scars, or markings from images 1 & 2 must be visible on exposed skin and must not appear on top of clothing.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +# ---------- Built-in Seedream Edit (1 face + 1 ref) prompt ---------- + +_SEEDREAM_EDIT_1FACE_PROMPT = r"""You are Gemini 2.5, an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. + +Primary Directive: Your task is to analyze Reference Image 2 (a complete scene) and generate a single, comprehensive prompt for Seedream 4.5. This prompt will instruct the model on how to use a total of two reference images. + +Critical Context (Non-negotiable): Seedream will always receive 2 reference images in this specific order: +Image 1: Provides the subject's complete face structure, facial features, and identity. +Image 2: The complete scene reference (this is the image you will be given to analyze). + +Your analysis must focus exclusively on Image 2. Your generated prompt must correctly instruct Seedream on this specific 2-image workflow. + +Your Generation Task: +You will be given Image 2. +You will analyze Image 2 ONLY. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. + +Mandatory Output Format (Strict Template): +Use reference image 1 for the subject's complete face, features, and identity. Use reference image 2 as the complete reference for all other elements: clothing, pose, action, body type, scene composition, background environment, lighting, and overall atmosphere. +Subject details: [Describe the subject's clothing in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the features.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +_SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT = r"""You are an expert at creating complete image generation prompts for Seedream 4.0 AI model. + +IMPORTANT CONTEXT: +- Seedream will receive 5 reference images in this order: + 1. Images 1-2: Face structure references + 2. Images 3-4: Body type and physique references + 3. Image 5: THIS image - complete scene reference +- You are analyzing image 5 ONLY +- Your output must be a COMPLETE prompt for Seedream + +YOUR TASK: +Analyze this image and create a complete Seedream prompt that instructs the AI how to use all references and describes everything visible in THIS image. + +OUTPUT FORMAT (mandatory structure): +"Use the first two reference images for the face structure. Use reference images 3-4 for the body type and physique. Use reference image 5 as the complete reference for clothing, pose, action, scene composition, background environment, lighting setup, and overall atmosphere. + +Subject details: [Describe the person's clothing in complete detail - every garment, accessories, jewelry, shoes, specific details like patterns, textures, colors, cuts, styles]. [Describe the exact pose - standing, sitting, body position, arm placement, leg position]. [Describe what the person is doing - their action, gesture, body language, facial expression like smiling/serious but WITHOUT describing facial features]. + +The scene: [describe location type and setting]. The environment features [describe architectural elements, furniture, props, and background in detail]. The setting is [indoor/outdoor details with spatial relationships]. + +Lighting: [describe light source, direction, quality, shadows, time of day, color temperature in technical detail]. + +Camera: [describe perspective, depth of field, focal distance, composition. For camera angle: default to 'eye-level' unless the angle is clearly extreme. If the camera is only slightly below eye level, describe it as 'approximately eye-level with a very subtle upward perspective.' If slightly above, use 'approximately eye-level, tilted marginally downward.' Always understate the angle by one level to compensate for Seedream's tendency to exaggerate]. + +Atmosphere: [describe mood, ambiance, weather if applicable, environmental effects]. + +Colors and textures: [describe dominant colors throughout the scene, materials, surface properties, color palette]. + +Technical quality: [high-resolution, sharp focus, professional photography, etc.]." + +CRITICAL RULES: +- DO describe: clothing (every detail), pose, action, body language, gesture, expression type (smile/serious) +- NEVER describe: hair color, hair style, eye color, facial features, skin tone, ethnic features +- Use "this person", "the subject" when referring to the individual +- Be extremely detailed about clothing and accessories +- Be precise about pose and body position +- Focus on EVERYTHING visible except facial/hair features +- CAMERA ANGLE DAMPENING: Seedream heavily amplifies camera angle descriptions. Always understate angles by one full level. Near eye-level → "eye-level." Slightly low → "approximately eye-level with a very subtle upward perspective." Moderately low → "slightly below eye-level." Only use "low angle" if the camera is clearly at knee height or below. Same rule applies upward. +- BANNED CAMERA TERMS: Never use "low-angle shot," "worm's-eye view," "looking up at," "shot from below," or "high-angle shot" unless the source image shows a genuinely extreme perspective. Prefer neutral terms like "eye-level," "approximately eye-level," or "slightly adjusted." + +Output ONLY the formatted prompt, nothing else.""" + + +# ---------- Vertex AI helpers ---------- + +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + + +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + from google.oauth2 import service_account + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +# ---------- Serve prompts to frontend ---------- + +try: + from server import PromptServer + from aiohttp import web + + @PromptServer.instance.routes.get("/ofm_prompt_generator/get_prompts") + async def _get_prompts(request): + return web.json_response({ + "JSON Image Analysis": _JSON_ANALYSIS_PROMPT, + "Style Transfer Prompt": _STYLE_TRANSFER_PROMPT, + "Seedream Edit (2 face + 1 ref)": _SEEDREAM_EDIT_PROMPT, + "Seedream Edit (1 face + 1 ref)": _SEEDREAM_EDIT_1FACE_PROMPT, + "Seedream Edit (2 face and body + 1 ref)": _SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT, + "Seedream Edit (2 faces + 2 bodies + 1ref)": _SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT, + "Custom Prompt": "", + }) +except Exception: + logging.warning("OFM Prompt Generator: could not register API routes (server not available)") + + +# ---------- Image encoding helper ---------- + +def _image_tensor_to_parts(images): + """Convert ComfyUI IMAGE tensor [B, H, W, C] to Gemini inlineData parts.""" + parts = [] + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype(np.uint8) + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + parts.append({"inlineData": {"mimeType": "image/png", "data": b64}}) + return parts + + +def _strip_markdown_fences(text): + """Remove markdown code fences like ```json ... ``` from the response.""" + text = re.sub(r'^```\w*\s*\n?', '', text) + text = re.sub(r'\n?```\s*$', '', text) + return text.strip() + + +# ---------- Node ---------- + +class GeminiPromptNode: + """OFM Prompt Generator — analyze images or generate prompts with Gemini.""" + + # Cache last known good API keys to survive auto-queue serialization drops + _cached_gemini_key = "" + _cached_grok_key = "" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "mode": (_PROMPT_MODES, {"default": "JSON Image Analysis"}), + "provider": (_PROVIDERS, {"default": "Gemini"}), + "gemini_api_key": ("STRING", {"default": "", "multiline": False}), + "grok_api_key": ("STRING", {"default": "", "multiline": False}), + }, + "optional": { + "images": ("IMAGE",), + "custom_prompt": ("STRING", { + "default": "", + "multiline": True, + }), + "vertex_json_path": ("STRING", { + "default": "", + "multiline": False, + "tooltip": "Chemin vers le fichier JSON service account Vertex AI (provider Vertex uniquement)", + }), + "gemini_model": (_GEMINI_MODELS, {"default": "gemini-2.5-pro"}), + "grok_model": (_GROK_MODELS, {"default": "grok-4.20-0309-reasoning"}), + "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}), + "max_tokens": ("INT", {"default": 8192, "min": 64, "max": 65536, "step": 64}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFF}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("prompt",) + FUNCTION = "generate" + OUTPUT_NODE = True + CATEGORY = "utils" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def generate(self, mode, provider="Gemini", gemini_api_key="", grok_api_key="", + images=None, custom_prompt="", + vertex_json_path="", + gemini_model="gemini-2.5-pro", grok_model="grok-3", + temperature=1.0, max_tokens=8192, + seed=0): + # Update cache when keys are provided, fall back to cache when empty + if gemini_api_key.strip(): + GeminiPromptNode._cached_gemini_key = gemini_api_key.strip() + if grok_api_key.strip(): + GeminiPromptNode._cached_grok_key = grok_api_key.strip() + + gemini_api_key = gemini_api_key.strip() or GeminiPromptNode._cached_gemini_key + grok_api_key = grok_api_key.strip() or GeminiPromptNode._cached_grok_key + + logging.info("OFM Prompt Generator: provider=%s, gemini_key_len=%d, grok_key_len=%d", + provider, len(gemini_api_key), len(grok_api_key)) + if provider == "Gemini": + api_key = gemini_api_key + if not api_key: + raise RuntimeError("OFM Prompt Generator: Gemini API key is required.") + elif provider == "Vertex": + api_key = "" + if not vertex_json_path.strip(): + raise RuntimeError("OFM Prompt Generator: vertex_json_path est requis pour le provider Vertex.") + else: + api_key = grok_api_key + if not api_key: + raise RuntimeError("OFM Prompt Generator: Grok API key is required.") + + # Pick the prompt based on mode + if mode == "JSON Image Analysis": + instruction = _JSON_ANALYSIS_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: an image is required for JSON Image Analysis mode.") + elif mode == "Style Transfer Prompt": + instruction = _STYLE_TRANSFER_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image is required for Style Transfer Prompt mode.") + elif mode == "Seedream Edit (2 face + 1 ref)": + instruction = _SEEDREAM_EDIT_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 3 - the scene) is required for Seedream Edit mode.") + elif mode == "Seedream Edit (1 face + 1 ref)": + instruction = _SEEDREAM_EDIT_1FACE_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 2 - the scene) is required for Seedream Edit mode.") + elif mode == "Seedream Edit (2 face and body + 1 ref)": + instruction = _SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 3 - the scene) is required for Seedream Edit (2 face and body + 1 ref) mode.") + elif mode == "Seedream Edit (2 faces + 2 bodies + 1ref)": + instruction = _SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 5 - the scene) is required for Seedream Edit (2 faces + 2 bodies + 1ref) mode.") + else: + instruction = custom_prompt.strip() + if not instruction: + raise RuntimeError("OFM Prompt Generator: custom_prompt cannot be empty in Custom Prompt mode.") + + if provider == "Grok": + text = self._call_grok(api_key, grok_model, instruction, images, temperature, max_tokens) + elif provider == "Vertex": + text = self._call_vertex(vertex_json_path, gemini_model, instruction, images, temperature, max_tokens) + else: + text = self._call_gemini(api_key, gemini_model, instruction, images, temperature, max_tokens) + + text = _strip_markdown_fences(text) + + # Prepend face-preservation instruction for JSON Image Analysis mode + if mode == "JSON Image Analysis": + face_prefix = ( + "Generate a high-quality photograph using ONLY the face and skin tone from reference image 1. " + "Use reference image 2 as the visual reference for everything else: hair, clothing, pose, body positioning, " + "styling, lighting, composition, background, color palette, mood, and all other visual details. " + "The following JSON analysis is a detailed breakdown of reference image 2 — follow it precisely:\n" + ) + text = face_prefix + text + + active_model = grok_model if provider == "Grok" else gemini_model + logging.info("OFM Prompt Generator: generated %d chars with %s", len(text), active_model) + return {"ui": {"text": [text]}, "result": (text,)} + + def _call_gemini(self, api_key, model, instruction, images, temperature, max_tokens): + url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}" + + parts = [] + if images is not None: + parts.extend(_image_tensor_to_parts(images)) + parts.append({"text": instruction}) + + payload = { + "contents": [{"parts": parts}], + "generationConfig": { + "temperature": temperature, + "maxOutputTokens": max_tokens, + }, + } + + try: + resp = requests.post(url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=180) + resp.raise_for_status() + data = resp.json() + except requests.exceptions.HTTPError as e: + msg = f"OFM Prompt Generator API error: {e.response.status_code}" + try: + body = e.response.json() + if "error" in body: + msg += f" — {body['error']}" + except Exception: + msg += f" — {e.response.text[:200]}" + raise RuntimeError(msg) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"OFM Prompt Generator request error: {e!s}") + + text = _extract_text(data) + if not text: + raise RuntimeError(f"OFM Prompt Generator: no text in response. {_response_summary(data)}") + return text + + def _call_vertex(self, json_path, model, instruction, images, temperature, max_tokens): + from google import genai + from google.genai import types + + credentials, project_id = _load_vertex_credentials(json_path) + print(f"\U0001f310 [Vertex AI] Connexion \u2014 projet={project_id} | location=us-central1 | mod\u00e8le={model}") + + client = genai.Client( + vertexai=True, + project=project_id, + location="us-central1", + credentials=credentials, + ) + + contents = [] + if images is not None: + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype("uint8") + pil = Image.fromarray(img_np) + contents.append(pil) + contents.append(instruction) + + config = types.GenerateContentConfig( + temperature=temperature, + max_output_tokens=max_tokens, + ) + + try: + response = client.models.generate_content( + model=model, + contents=contents, + config=config, + ) + except Exception as e: + raise RuntimeError(f"OFM Prompt Generator (Vertex) erreur API : {e}") + + text = "" + try: + for part in response.candidates[0].content.parts: + if getattr(part, "thought", False): + continue + if hasattr(part, "text") and part.text: + text += part.text + except Exception: + pass + if not text: + try: + text = response.text or "" + except Exception: + pass + if not text: + raise RuntimeError("OFM Prompt Generator (Vertex) : aucun texte dans la r\u00e9ponse.") + return text.strip() + + def _call_grok(self, api_key, grok_model, instruction, images, temperature, max_tokens): + url = "https://api.x.ai/v1/chat/completions" + + # Build message content + content = [] + if images is not None: + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype("uint8") + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + content.append({ + "type": "image_url", + "image_url": {"url": f"data:image/png;base64,{b64}"}, + }) + content.append({"type": "text", "text": instruction}) + + payload = { + "model": grok_model, + "messages": [{"role": "user", "content": content}], + "temperature": temperature, + "max_completion_tokens": max_tokens, + } + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + } + + try: + resp = requests.post(url, json=payload, headers=headers, timeout=180) + resp.raise_for_status() + data = resp.json() + except requests.exceptions.HTTPError as e: + msg = f"OFM Prompt Generator (Grok) API error: {e.response.status_code}" + try: + body = e.response.json() + if "error" in body: + msg += f" \u2014 {body['error']}" + except Exception: + msg += f" \u2014 {e.response.text[:200]}" + raise RuntimeError(msg) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"OFM Prompt Generator (Grok) request error: {e!s}") + + choices = data.get("choices", []) + if not choices: + raise RuntimeError("OFM Prompt Generator (Grok): no choices in API response.") + text = choices[0].get("message", {}).get("content", "") + if not text: + raise RuntimeError("OFM Prompt Generator (Grok): empty response from API.") + return text + + +def _extract_text(data): + """Extract concatenated text from Gemini response, skipping thought parts.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + return None + parts = candidates[0].get("content", {}).get("parts") or [] + texts = [] + for part in parts: + if part.get("thought"): + continue + if "text" in part: + texts.append(part["text"]) + return "\n".join(texts).strip() if texts else None + except (KeyError, TypeError): + return None + + +def _response_summary(data): + """Summarize why the response had no usable text.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + block = data.get("promptFeedback", {}).get("blockReason", "") + if block: + return f"Prompt blocked: {block}" + return "No candidates returned." + reason = candidates[0].get("finishReason", "") + return f"finishReason={reason}" + except Exception: + return "" diff --git a/aiorbust-ofm-pack-main/_backups/20260424_212126_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260424_212126_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..9dbf4475d5a6ddb24cfa94197ba7728eca42c91f --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260424_212126_nano_banana_aio.py @@ -0,0 +1,6366 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_path": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin complet vers le fichier JSON du service account.", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if not prompt or not prompt.strip(): + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_path = (vertex_json_path or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_path = vj_path, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + # ── Vertex n'accepte pas les requêtes simultanées ── + if provider == "VERTEX": + batch_size = 1 + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_path = vj_path, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_path: + return self._handle_error( + "❌ vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_path=vj_path, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_path=vj_path, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + ): + if not vertex_json_path: + return self._handle_error("❌ vertex_json_path manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, vertex_json_path, vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + vertex_json_path, vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, vertex_json_path, vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_path="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Automation] vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 480p ou 720p uniquement (pas de 1080p, pas de 4K) + if model in _SEEDANCE_MODELS and video_resolution in ("1080p", "4K"): + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas {video_resolution} → snap vers 720p") + video_resolution = "720p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Video] vertex_json_path manquant pour le provider VERTEX." + ) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260424_212647_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260424_212647_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..9dbf4475d5a6ddb24cfa94197ba7728eca42c91f --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260424_212647_nano_banana_aio.py @@ -0,0 +1,6366 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_path": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin complet vers le fichier JSON du service account.", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if not prompt or not prompt.strip(): + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_path = (vertex_json_path or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_path = vj_path, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + # ── Vertex n'accepte pas les requêtes simultanées ── + if provider == "VERTEX": + batch_size = 1 + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_path = vj_path, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_path: + return self._handle_error( + "❌ vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_path=vj_path, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_path=vj_path, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + ): + if not vertex_json_path: + return self._handle_error("❌ vertex_json_path manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, vertex_json_path, vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + vertex_json_path, vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, vertex_json_path, vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_path="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Automation] vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 480p ou 720p uniquement (pas de 1080p, pas de 4K) + if model in _SEEDANCE_MODELS and video_resolution in ("1080p", "4K"): + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas {video_resolution} → snap vers 720p") + video_resolution = "720p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Video] vertex_json_path manquant pour le provider VERTEX." + ) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260424_213019_nb_aio_faceswap.js b/aiorbust-ofm-pack-main/_backups/20260424_213019_nb_aio_faceswap.js new file mode 100644 index 0000000000000000000000000000000000000000..6089c26ae6118eef450df5ee6d9bbc1eb50d06fe --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260424_213019_nb_aio_faceswap.js @@ -0,0 +1,1134 @@ +/** + * NanoBananaAIO — Automation Face Swap UI + Image/Video Mode Toggle + * Bloc visuel distinctif avec toggle ON/OFF, verrouillage des widgets, + * restriction du modèle à NBPro/NB2, et option Breast Refiner. + * + Toggle IMAGE / VIDEO avec support Veo 3 (Google & Vertex). + */ +import { app } from "../../scripts/app.js"; +// ─── Constantes mode vidéo ───────────────────────────────────────────────── +const VIDEO_MODELS = ["Veo 3.1 Lite", "Veo 3.1", "Veo 3.1 Fast", "Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control", "Seedance 2.0"]; +const IMAGE_MODELS_DEFAULT = ["Nano Banana Pro", "Nano Banana 2", "Seedream 4.5", "GPT Image 2.0"]; +const VIDEO_ASPECT_RATIOS = ["16:9", "9:16"]; +const IMAGE_ASPECT_RATIOS = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"]; +const VIDEO_RESOLUTIONS = ["480p", "720p", "1080p", "4K"]; +const KLING30_MODELS = ["Kling 3.0"]; +const IMAGE_RESOLUTIONS = ["1K", "2K", "4K"]; +const SEEDANCE_MODELS = ["Seedance 2.0"]; +// ─── Widgets verrouillés en mode automation ──────────────────────────────── +const LOCKABLE_WIDGETS = [ + "prompt", + "negative_prompt", + "use_search", + "system_instructions", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", +]; +const AUTOMATION_MODELS = ["Nano Banana Pro", "Nano Banana 2"]; +// ─── Helpers ─────────────────────────────────────────────────────────────── +function getWidget(node, name) { + return node.widgets?.find(w => w.name === name); +} +/** Synchronise un widget Python caché avec une valeur JS. */ +function syncNodeWidget(node, name, value) { + const w = getWidget(node, name); + if (w) { + w.value = value; + if (w.callback) w.callback(value); + } +} +/** Masque ou affiche un widget standard (computeSize trick). */ +function setWidgetVisible(node, widgetName, visible) { + const w = getWidget(node, widgetName); + if (!w) return; + if (visible) { + if (w._modeOrigComputeSize !== undefined) { + w.computeSize = w._modeOrigComputeSize; + delete w._modeOrigComputeSize; + } else { + delete w.computeSize; + } + w.disabled = false; + w.hidden = false; + } else { + if (w._modeOrigComputeSize === undefined) { + w._modeOrigComputeSize = w.computeSize; + } + w.computeSize = () => [0, -4]; + w.disabled = true; + w.hidden = true; + } + if (w.inputEl) w.inputEl.style.display = visible ? "" : "none"; + if (w.element) w.element.style.display = visible ? "" : "none"; +} +function setWidgetLocked(node, widgetName, locked) { + const w = getWidget(node, widgetName); + if (!w) return; + w.disabled = locked; + const applyStyle = (el) => { + if (!el || !el.style) return; + el.style.opacity = locked ? "0.3" : "1.0"; + el.style.pointerEvents = locked ? "none" : "auto"; + el.style.filter = locked ? "grayscale(60%)" : "none"; + }; + if (w.inputEl) { + w.inputEl.disabled = locked; + applyStyle(w.inputEl); + // Les widgets multiline (negative_prompt, system_instructions) sont + // wrappés dans un parent
; on applique aussi l'effet dessus. + applyStyle(w.inputEl.parentElement); + } + applyStyle(w.element); +} +/** + * Redirige les événements wheel du container DOM vers le canvas LiteGraph, + * pour que le zoom ComfyUI fonctionne même quand la souris survole un widget DOM. + */ +function forwardWheelToCanvas(el) { + el.addEventListener("wheel", (e) => { + e.preventDefault(); + e.stopPropagation(); + const canvas = app.canvas?.canvas; + if (!canvas) return; + canvas.dispatchEvent(new WheelEvent("wheel", { + bubbles: true, cancelable: true, view: window, + deltaX: e.deltaX, deltaY: e.deltaY, deltaZ: e.deltaZ, deltaMode: e.deltaMode, + clientX: e.clientX, clientY: e.clientY, screenX: e.screenX, screenY: e.screenY, + ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, metaKey: e.metaKey, + })); + }, { passive: false }); +} +/** + * Applique / retire l'état automation au node (verrouille les widgets + * et restreint la liste des modèles à NBPro/NB2). + */ +function applyAutomationState(node, enabled) { + const applyLocks = () => { + for (const name of LOCKABLE_WIDGETS) setWidgetLocked(node, name, enabled); + }; + // Passe immédiate, puis plusieurs passes différées pour rattraper les + // widgets multiline (negative_prompt, system_instructions) dont l'inputEl + // n'est parfois rattaché au DOM qu'après un ou deux frames. + applyLocks(); + requestAnimationFrame(applyLocks); + setTimeout(applyLocks, 100); + setTimeout(applyLocks, 400); + const modelWidget = getWidget(node, "model"); + if (!modelWidget) return; + if (enabled) { + if (modelWidget.options?.values) { + modelWidget.options.values = [...AUTOMATION_MODELS]; + } + if (!AUTOMATION_MODELS.includes(modelWidget.value)) { + modelWidget.value = "Nano Banana Pro"; + if (modelWidget.callback) modelWidget.callback("Nano Banana Pro"); + } + } else { + // Restaurer la liste selon le mode courant — Python déclare image+vidéo + // donc on ne peut plus se fier à _fsOrigValues comme source de vérité. + const correctModels = node._nbIsVideoMode ? VIDEO_MODELS : IMAGE_MODELS_DEFAULT; + if (modelWidget.options?.values) modelWidget.options.values = [...correctModels]; + // S'assurer que la valeur courante est dans la liste restaurée + if (!correctModels.includes(modelWidget.value)) { + modelWidget.value = correctModels[0]; + if (modelWidget.callback) modelWidget.callback(correctModels[0]); + } + } + modelWidget.disabled = false; + app.graph.setDirtyCanvas(true, true); +} +// ─── Sync aspect_ratio : grisé si Kling (any) + WAVESPEED en mode vidéo ──────── +// KLING_MODELS — conservé pour référence future, plus utilisé pour le verrouillage aspect_ratio +// (Kling supporte 16:9 et 9:16, les deux valeurs de VIDEO_ASPECT_RATIOS) +const KLING_MODELS = ["Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"]; +// GPT Image 2.0 — aspect ratios supportés (filtre automatique du dropdown) +const GPT2_ASPECT_RATIOS = ["1:1", "4:3", "3:4", "16:9", "9:16"]; +const GPT2_NEAREST_AR = { + "2:3": "9:16", "3:2": "16:9", "4:5": "3:4", "5:4": "4:3", "21:9": "16:9", +}; +function setupKlingAspectRatioSync(node) { + // Kling supporte 16:9 ET 9:16 — le dropdown est déjà restreint à VIDEO_ASPECT_RATIOS + // en mode vidéo, donc aucun verrouillage supplémentaire n'est nécessaire. + // La fonction reste en place pour compatibilité avec les appels existants. + node._nbSyncKlingAspectRatio = () => {}; +} +// ─── Contraintes de durée par modèle vidéo ──────────────────────────────────── +const DURATION_CONSTRAINTS = { + "Kling 2.6": { min: 5, max: 10, step: 5, tooltip: "⚠️ Kling 2.6 only supports 5s or 10s. Any other value will be rounded automatically." }, + "Kling 3.0": { min: 3, max: 15, step: 1, tooltip: "" }, + "Kling 3.0 Motion Control": { min: 3, max: 15, step: 1, tooltip: "ℹ️ Motion Control: output duration equals the reference video's duration." }, + "Seedance 2.0": { min: 4, max: 15, step: 1, tooltip: "⚠️ Seedance 2.0 : image-to-video uniquement." }, + _veo: { min: 4, max: 8, step: 1, tooltip: "" }, +}; +function getDurationConstraint(model) { + return DURATION_CONSTRAINTS[model] ?? DURATION_CONSTRAINTS._veo; +} + +// ─── Sync video_duration selon le modèle ────────────────────────────────────── +function setupKlingDurationSync(node) { + const modelWidget = getWidget(node, "model"); + const durationWidget = getWidget(node, "video_duration"); + if (!modelWidget || !durationWidget) return; + + /** Clamp une valeur dans [min, max] en respectant step. */ + const clampDuration = (v, { min, max, step }) => { + let clamped = Math.max(min, Math.min(max, parseInt(v) || min)); + // Pour step > 1 (ex. Kling 2.6 : step=5) : snap sur le multiple le plus proche + if (step > 1) { + const steps = Math.round((clamped - min) / step); + clamped = min + steps * step; + } + return Math.max(min, Math.min(max, clamped)); + }; + + /** Recalibre min/max/step et snappe la valeur si besoin. */ + const syncDuration = () => { + if (!node._nbIsVideoMode) return; + const c = getDurationConstraint(modelWidget.value); + if (durationWidget.options) { + durationWidget.options.min = c.min; + durationWidget.options.max = c.max; + durationWidget.options.step = c.step; + } + durationWidget.tooltip = c.tooltip; + const clamped = clampDuration(durationWidget.value, c); + if (durationWidget.value !== clamped) { + durationWidget.value = clamped; + if (durationWidget.callback) durationWidget.callback(clamped); + } + node.setDirtyCanvas(true); + }; + + node._nbSyncKlingDuration = syncDuration; + syncDuration(); + + // Hooker le changement de modèle → recalibrer la durée + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncDuration(); + }; +} +// ─── Sync batch_size selon provider et mode vidéo ───────────────────────── +function setupProviderBatchSync(node) { + const providerWidget = getWidget(node, "provider"); + const batchSizeWidget = getWidget(node, "batch_size"); + if (!providerWidget || !batchSizeWidget) return; + const syncBatchState = () => { + const isVertex = providerWidget.value === "VERTEX"; + const isVideo = node._nbIsVideoMode === true; + const shouldLock = isVertex || isVideo; + batchSizeWidget.disabled = shouldLock; + if (shouldLock) batchSizeWidget.value = 1; + node.setDirtyCanvas(true); + }; + // Expose pour que les fonctions activateVideoMode / activateImageMode + // puissent déclencher une resynchronisation sans passer par le callback + // du widget provider. + node._nbSyncBatchState = syncBatchState; + syncBatchState(); + const origCallback = providerWidget.callback; + providerWidget.callback = function (...args) { + if (origCallback) origCallback.apply(this, args); + syncBatchState(); + }; +} +// ─── Sync image_size (résolution) selon le modèle vidéo ───────────────────── +// Seedance 2.0 : 480p / 720p uniquement (pas de 1080p) +// Autres modèles vidéo : 720p / 1080p uniquement (pas de 480p) +function setupVideoResolutionSync(node) { + const modelWidget = getWidget(node, "model"); + const imgSizeWidget = getWidget(node, "image_size"); + if (!modelWidget || !imgSizeWidget) return; + + const syncResolution = () => { + if (!node._nbIsVideoMode) return; + const model = modelWidget.value; + const isSeedance = SEEDANCE_MODELS.includes(model); + const isKling30 = KLING30_MODELS.includes(model); + + let allowedRes, defaultRes; + if (isSeedance) { + allowedRes = ["480p", "720p"]; + defaultRes = "720p"; + } else if (isKling30) { + allowedRes = ["720p", "1080p", "4K"]; + defaultRes = "1080p"; + } else { + allowedRes = ["720p", "1080p"]; + defaultRes = "1080p"; + } + + if (imgSizeWidget.options?.values) imgSizeWidget.options.values = [...allowedRes]; + if (!allowedRes.includes(imgSizeWidget.value)) { + imgSizeWidget.value = defaultRes; + if (imgSizeWidget.callback) imgSizeWidget.callback(defaultRes); + } + // Tooltip sur le widget modèle pour indiquer image-to-video uniquement + if (modelWidget.options) { + modelWidget.options.tooltip = isSeedance + ? "⚠️ Image-to-video uniquement" + : ""; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncVideoResolution = syncResolution; + + // Hooker le changement de modèle → recalibrer la résolution + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncResolution(); + }; +} +// ─── Sync aspect_ratio et gpt2_image_quality selon le modèle ───────────── +function setupGPT2Sync(node) { + const modelWidget = getWidget(node, "model"); + const arWidget = getWidget(node, "aspect_ratio"); + if (!modelWidget || !arWidget) return; + + /** Retourne le ratio le plus proche supporté par GPT2. */ + function nearestGPT2AR(value) { + if (GPT2_ASPECT_RATIOS.includes(value)) return value; + return GPT2_NEAREST_AR[value] || "1:1"; + } + + /** Applique ou retire le filtre GPT2 sur le dropdown aspect_ratio. */ + const syncAR = () => { + const isGPT2 = (modelWidget.value === "GPT Image 2.0"); + if (isGPT2) { + if (arWidget.options?.values) arWidget.options.values = [...GPT2_ASPECT_RATIOS]; + const snapped = nearestGPT2AR(arWidget.value); + if (arWidget.value !== snapped) { + arWidget.value = snapped; + if (arWidget.callback) arWidget.callback(snapped); + } + } else { + // Restaure la liste complète selon le mode courant + const fullList = node._nbIsVideoMode ? VIDEO_ASPECT_RATIOS : IMAGE_ASPECT_RATIOS; + if (arWidget.options?.values) arWidget.options.values = [...fullList]; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncGPT2AR = syncAR; + syncAR(); + + // Hooker le changement de modèle + const origCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origCb) origCb.apply(this, args); + syncAR(); + }; +} +// ─── Factorisation des styles des boutons ON/OFF ────────────────────────── +// Évite de dupliquer 8 lignes de style à chaque toggle (Face Swap, Breast +// Refiner, Low Neck). Chaque bouton a sa propre palette "ON". +const TOGGLE_OFF_CSS = { + text: "OFF", + background: "#3a3a3a", + color: "#888", + border: "1.5px solid #666", + boxShadow: "none", +}; +/** + * Applique l'état visuel ON/OFF à un bouton bascule. + * @param {HTMLButtonElement} btn + * @param {boolean} on + * @param {{bg:string, text?:string, border:string, glow:string}} onStyle + */ +function setToggleVisual(btn, on, onStyle) { + if (on) { + btn.textContent = onStyle.text || "ON"; + btn.style.background = onStyle.bg; + btn.style.color = "#fff"; + btn.style.border = `1.5px solid ${onStyle.border}`; + btn.style.boxShadow = `0 0 8px ${onStyle.glow}`; + } else { + btn.textContent = TOGGLE_OFF_CSS.text; + btn.style.background = TOGGLE_OFF_CSS.background; + btn.style.color = TOGGLE_OFF_CSS.color; + btn.style.border = TOGGLE_OFF_CSS.border; + btn.style.boxShadow = TOGGLE_OFF_CSS.boxShadow; + } +} +const FS_ON_STYLE = { bg: "#00c853", border: "#00e676", glow: "rgba(0,200,83,0.5)" }; +const BR_ON_STYLE = { bg: "#c2185b", border: "#f50057", glow: "rgba(245,0,87,0.4)" }; +const LN_ON_STYLE = { bg: "#6a1b9a", border: "#ab47bc", glow: "rgba(171,71,188,0.4)" }; +// CSS de base partagé par les 3 boutons ON/OFF (même taille, même rayon) +const TOGGLE_BTN_BASE_CSS = ` + padding: 4px 18px; + border-radius: 14px; + border: 1.5px solid #666; + background: #3a3a3a; + color: #888; + font-weight: 700; + font-size: 11px; + cursor: pointer; + min-width: 55px; + letter-spacing: 0.5px; + transition: all 0.2s ease; +`; +// ─── Image / Video mode toggle ──────────────────────────────────────────── +function buildModeToggle(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #1565c0; + border-radius: 9px; + padding: 8px 10px 11px 10px; + background: linear-gradient(135deg, + rgba(21,101,192,0.14) 0%, + rgba(79,195,247,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Titre ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ GENERATION MODE"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #4fc3f7; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(79,195,247,0.45); + margin-bottom: 7px; + user-select: none; + transition: color 0.25s, text-shadow 0.25s; + `; + container.appendChild(titleEl); + // ── Séparateur ──────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #1565c0 40%, #1565c0 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Boutons IMAGE / VIDÉO côte à côte ───────────────────────────────── + const btnRow = document.createElement("div"); + btnRow.style.cssText = "display:flex; gap:8px;"; + function makeChoiceBtn(label, active) { + const btn = document.createElement("button"); + btn.textContent = label; + btn.style.cssText = ` + flex: 1; + padding: 6px 4px; + border-radius: 8px; + border: 1.5px solid ${active ? "#4fc3f7" : "#444"}; + background: ${active ? "rgba(79,195,247,0.18)" : "#252525"}; + color: ${active ? "#4fc3f7" : "#555"}; + font-weight: 700; + font-size: 11px; + cursor: pointer; + letter-spacing: 1px; + box-shadow: ${active ? "0 0 7px rgba(79,195,247,0.25)" : "none"}; + transition: all 0.2s ease; + `; + return btn; + } + const imgBtn = makeChoiceBtn("🖼 IMAGES", true); + const vidBtn = makeChoiceBtn("🎬 VIDÉO", false); + btnRow.appendChild(imgBtn); + btnRow.appendChild(vidBtn); + container.appendChild(btnRow); + // ── État ────────────────────────────────────────────────────────────── + let isVideoMode = false; + const GREY_IN_VIDEO = [ + "temperature", "top_p", "negative_prompt", + "fal_safety_tolerance", "fal_enable_web_search", + "use_search", "system_instructions", "batch_size", + "gpt2_image_quality", + ]; + // ── Grise/dégrise le bloc Automation Face Swap ─────────────────────── + function setFaceSwapGreyed(greyed) { + const fsW = node.widgets?.find(w => w.name === "nb_faceswap_automation"); + const el = fsW?.element; + if (!el) return; + el.style.opacity = greyed ? "0.22" : "1"; + el.style.pointerEvents = greyed ? "none" : "auto"; + el.style.filter = greyed ? "grayscale(80%) brightness(0.35)" : "none"; + app.graph.setDirtyCanvas(true, true); + } + function updateCombo(name, newValues, newDefault) { + const w = getWidget(node, name); + if (!w) return; + if (w.options?.values) w.options.values = [...newValues]; + if (!newValues.includes(w.value)) { + w.value = newDefault; + if (w.callback) w.callback(newDefault); + } + } + // ── Visibilité des widgets vidéo-only ───────────────────────────────── + // Ces widgets sont visibles SI ET SEULEMENT SI on est en mode VIDEO. + function updateVideoOnlyWidgets(visible) { + setWidgetVisible(node, "video_duration", visible); + setWidgetVisible(node, "video_generate_audio", visible); + } + function updateVideoDurationVisibility() { updateVideoOnlyWidgets(node._nbIsVideoMode === true); } + node._nbUpdateVideoDuration = updateVideoDurationVisibility; + // ── Activer le mode IMAGE ───────────────────────────────────────────── + function activateImageMode(initial = false) { + isVideoMode = false; + node._nbIsVideoMode = false; + imgBtn.style.border = "1.5px solid #4fc3f7"; + imgBtn.style.background = "rgba(79,195,247,0.18)"; + imgBtn.style.color = "#4fc3f7"; + imgBtn.style.boxShadow = "0 0 7px rgba(79,195,247,0.25)"; + vidBtn.style.border = "1.5px solid #444"; + vidBtn.style.background = "#252525"; + vidBtn.style.color = "#555"; + vidBtn.style.boxShadow = "none"; + container.style.border = "2px solid #1565c0"; + container.style.background = "linear-gradient(135deg, rgba(21,101,192,0.14) 0%, rgba(79,195,247,0.06) 100%)"; + titleEl.style.color = "#4fc3f7"; + titleEl.style.textShadow = "0 0 10px rgba(79,195,247,0.45)"; + // IMAGE_MODELS_DEFAULT = source de vérité (Python déclare image+vidéo + // pour la validation serveur, donc options.values n'est plus fiable) + const modelW = getWidget(node, "model"); + if (modelW) { + const vals = IMAGE_MODELS_DEFAULT; + if (modelW.options?.values) modelW.options.values = [...vals]; + if (!vals.includes(modelW.value)) { + modelW.value = vals[0]; + if (modelW.callback) modelW.callback(vals[0]); + } + if (modelW._imgOrigTooltip !== undefined) { + if (modelW.options) modelW.options.tooltip = modelW._imgOrigTooltip; + delete modelW._imgOrigTooltip; + } + } + updateCombo("aspect_ratio", IMAGE_ASPECT_RATIOS, "1:1"); + updateCombo("image_size", IMAGE_RESOLUTIONS, "2K"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "image_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, false); + // Re-synchronise batch_size et aspect_ratio (Kling) en mode image + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(false), 60); + if (!initial) { + syncNodeWidget(node, "video_mode_enabled", false); + app.graph.setDirtyCanvas(true, true); + } + } + // ── Activer le mode VIDÉO ───────────────────────────────────────────── + function activateVideoMode() { + isVideoMode = true; + node._nbIsVideoMode = true; + vidBtn.style.border = "1.5px solid #ce93d8"; + vidBtn.style.background = "rgba(206,147,216,0.18)"; + vidBtn.style.color = "#ce93d8"; + vidBtn.style.boxShadow = "0 0 7px rgba(206,147,216,0.3)"; + imgBtn.style.border = "1.5px solid #444"; + imgBtn.style.background = "#252525"; + imgBtn.style.color = "#555"; + imgBtn.style.boxShadow = "none"; + container.style.border = "2px solid #6a1b9a"; + container.style.background = "linear-gradient(135deg, rgba(106,27,154,0.14) 0%, rgba(206,147,216,0.06) 100%)"; + titleEl.style.color = "#ce93d8"; + titleEl.style.textShadow = "0 0 10px rgba(206,147,216,0.45)"; + // VIDEO_MODELS = source de vérité — pas de sauvegarde _imgOrigValues + // car options.values contient maintenant image+vidéo côté Python + const modelW = getWidget(node, "model"); + if (modelW) { + if (modelW.options?.values) modelW.options.values = [...VIDEO_MODELS]; + if (!VIDEO_MODELS.includes(modelW.value)) { + modelW.value = VIDEO_MODELS[0]; + if (modelW.callback) modelW.callback(VIDEO_MODELS[0]); + } + if (modelW.options?.tooltip) { + modelW._imgOrigTooltip = modelW.options.tooltip; + modelW.options.tooltip = ""; + } + } + updateCombo("aspect_ratio", VIDEO_ASPECT_RATIOS, "16:9"); + updateCombo("image_size", VIDEO_RESOLUTIONS, "1080p"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "video_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, true); + // Force batch_size = 1, synchronise aspect_ratio, durée et résolution selon le modèle + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + node._nbSyncKlingDuration?.(); + node._nbSyncVideoResolution?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(true), 60); + syncNodeWidget(node, "video_mode_enabled", true); + app.graph.setDirtyCanvas(true, true); + } + // ── Listeners ───────────────────────────────────────────────────────── + imgBtn.addEventListener("click", () => { if (isVideoMode) activateImageMode(); }); + vidBtn.addEventListener("click", () => { if (!isVideoMode) activateVideoMode(); }); + node._modeToggleAPI = { activateImageMode, activateVideoMode }; + // ── État initial SYNCHRONE (mode image par défaut) ──────────────────── + // Masquer video_duration AVANT d'ajouter le DOM widget évite un + // redimensionnement visible du node ~250 ms après le démarrage. + node._nbIsVideoMode = false; + updateVideoOnlyWidgets(false); + // ── Ajout DOM widget ────────────────────────────────────────────────── + const domWidget = node.addDOMWidget( + "nb_mode_toggle", "mode_toggle_div", container, + { serialize: false, hideOnZoom: false } + ); + if (domWidget) domWidget.computeSize = (w) => [w, 95]; + // ── Placer en PREMIER ───────────────────────────────────────────────── + if (domWidget) { + const idx = node.widgets.indexOf(domWidget); + if (idx > 0) { node.widgets.splice(idx, 1); node.widgets.unshift(domWidget); } + app.graph.setDirtyCanvas(true, true); + } + // ── Filtrage initial du dropdown "model" (mode image par défaut) ───── + // On ne fait QUE filtrer la liste — pas d'appel à activateImageMode() + // pour éviter de déclencher des callbacks qui perturbent la visibilité + // des widgets DOM (inputEl créés après le premier rendu). + setTimeout(() => { + const modelW = getWidget(node, "model"); + if (!modelW || node._nbIsVideoMode) return; + if (modelW.options?.values) modelW.options.values = [...IMAGE_MODELS_DEFAULT]; + if (!IMAGE_MODELS_DEFAULT.includes(modelW.value)) modelW.value = IMAGE_MODELS_DEFAULT[0]; + }, 200); + // ── Sync UI ↔ widget "video_mode_enabled" après chargement workflow ── + // Au chargement d'un workflow, ComfyUI restaure la valeur du widget + // caché `video_mode_enabled`, mais la variable locale isVideoMode reste + // à false. Résultat : l'UI montre IMAGES mais le backend reçoit + // video_mode_enabled=true → "Modèle vidéo inconnu : Nano Banana Pro". + // On fixe ça en synchronisant l'UI avec la valeur réelle du widget ~350ms + // après le onNodeCreated (délai suffisant pour que configure() ait injecté + // les valeurs sauvegardées). + setTimeout(() => { + const videoModeWidget = getWidget(node, "video_mode_enabled"); + const savedIsVideo = videoModeWidget?.value === true; + if (savedIsVideo && !node._nbIsVideoMode) { + // Workflow sauvegardé en mode vidéo → bascule l'UI en vidéo + activateVideoMode(); + } else { + // Force explicitement le widget à false pour éviter qu'une + // valeur "truthy" résiduelle (1, "true"…) passe côté Python + syncNodeWidget(node, "video_mode_enabled", false); + } + }, 350); +} +// ─── Automation Face Swap UI ────────────────────────────────────────────── +function buildFaceSwapUI(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #e65c00; + border-radius: 9px; + padding: 9px 10px 16px 10px; + background: linear-gradient(135deg, + rgba(230,92,0,0.13) 0%, + rgba(255,140,0,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Title ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ AUTOMATION FACE SWAP"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #ff8c00; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(255,140,0,0.45); + margin-bottom: 7px; + transition: color 0.25s, text-shadow 0.25s; + user-select: none; + `; + container.appendChild(titleEl); + // ── Separator ───────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #e65c00 40%, #e65c00 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Info hint ───────────────────────────────────────────────────────── + const hintEl = document.createElement("div"); + hintEl.textContent = "ℹ️ Image 1 = reference face · Image 2 = face to swap"; + hintEl.style.cssText = ` + font-size: 10px; + color: #999; + font-style: italic; + text-align: center; + margin-bottom: 8px; + user-select: none; + `; + container.appendChild(hintEl); + // ── Helper pour construire une ligne "label + bouton ON/OFF" ────────── + function makeToggleRow(labelText, tooltip, hidden = false) { + const row = document.createElement("div"); + row.style.cssText = ` + display: ${hidden ? "none" : "flex"}; + align-items: center; + gap: 8px; + ${hidden ? "margin-top: 8px; padding-top: 7px; border-top: 1px solid rgba(230,92,0,0.3);" : ""} + `; + const label = document.createElement("span"); + label.textContent = labelText; + label.title = tooltip; + label.style.cssText = ` + font-size: 12px; + color: #ccc; + flex: 1; + user-select: none; + `; + const btn = document.createElement("button"); + btn.textContent = "OFF"; + btn.title = tooltip; + btn.style.cssText = TOGGLE_BTN_BASE_CSS; + row.appendChild(label); + row.appendChild(btn); + return { row, btn }; + } + // ── Face Swap toggle ────────────────────────────────────────────────── + const { row: toggleRow, btn: toggleBtn } = makeToggleRow( + "Face Swap", + "Activate to run Automation Face Swap.\nImage 1 = reference face · Image 2 = face to swap", + false + ); + container.appendChild(toggleRow); + // ── Breast Refiner row (hidden until automation ON) ────────────────── + const { row: brRow, btn: brBtn } = makeToggleRow( + "Breast Refiner", + "This tool enhances breast shape by defining the upper curve for a more natural look. May trigger NSFW restrictions.", + true + ); + container.appendChild(brRow); + // ── Low Neck row (hidden until automation ON) ──────────────────────── + const { row: lnRow, btn: lnBtn } = makeToggleRow( + "Low Neck", + "Add a low neck, might be flagged as sensitive content.", + true + ); + container.appendChild(lnRow); + // ── Facial Expression section (hidden until automation ON) ─────────── + const EXPRESSIONS = [ + "Neutral", "Sensual", "Playful", "Subtle smile", "Smile", "Laugh", + ]; + const exprSection = document.createElement("div"); + exprSection.style.cssText = ` + display: none; + flex-direction: column; + gap: 6px; + margin-top: 8px; + padding-top: 7px; + border-top: 1px solid rgba(230,92,0,0.3); + `; + const exprTitleEl = document.createElement("div"); + exprTitleEl.textContent = "Facial Expression"; + exprTitleEl.style.cssText = ` + font-size: 11px; + font-weight: 600; + color: #aaa; + letter-spacing: 0.8px; + user-select: none; + `; + exprSection.appendChild(exprTitleEl); + const exprGrid = document.createElement("div"); + exprGrid.style.cssText = ` + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 4px; + `; + const exprBtns = {}; + function selectExpression(value) { + for (const [v, btn] of Object.entries(exprBtns)) { + const active = (v === value); + btn.style.background = active ? "rgba(255,140,0,0.35)" : "#2a2a2a"; + btn.style.color = active ? "#ff8c00" : "#888"; + btn.style.border = active ? "1.5px solid #e65c00" : "1.5px solid #444"; + btn.style.fontWeight = active ? "700" : "400"; + } + syncNodeWidget(node, "face_expression", value); + } + for (const value of EXPRESSIONS) { + const btn = document.createElement("button"); + btn.textContent = value; + btn.style.cssText = ` + padding: 4px 6px; + border-radius: 10px; + border: 1.5px solid #444; + background: #2a2a2a; + color: #888; + font-size: 10.5px; + cursor: pointer; + transition: all 0.15s ease; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; + btn.addEventListener("click", () => selectExpression(value)); + exprBtns[value] = btn; + exprGrid.appendChild(btn); + } + exprSection.appendChild(exprGrid); + container.appendChild(exprSection); + selectExpression("Neutral"); + // ── State ───────────────────────────────────────────────────────────── + let automationActive = false; + let breastRefinerActive = false; + let lowNeckActive = false; + const FS_HEIGHT_OFF = 115; + const FS_HEIGHT_ON = 300; + let _blockH = FS_HEIGHT_OFF; + // ── Face Swap toggle ────────────────────────────────────────────────── + toggleBtn.addEventListener("click", () => { + automationActive = !automationActive; + _blockH = automationActive ? FS_HEIGHT_ON : FS_HEIGHT_OFF; + setToggleVisual(toggleBtn, automationActive, FS_ON_STYLE); + if (automationActive) { + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + } else { + container.style.border = "2px solid #e65c00"; + container.style.background = "linear-gradient(135deg, rgba(230,92,0,0.13) 0%, rgba(255,140,0,0.06) 100%)"; + titleEl.style.color = "#ff8c00"; + titleEl.style.textShadow = "0 0 10px rgba(255,140,0,0.45)"; + brRow.style.display = "none"; + lnRow.style.display = "none"; + exprSection.style.display = "none"; + // Reset sub-toggles when automation is switched off + if (breastRefinerActive) { + breastRefinerActive = false; + setToggleVisual(brBtn, false, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", false); + } + if (lowNeckActive) { + lowNeckActive = false; + setToggleVisual(lnBtn, false, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", false); + } + } + applyAutomationState(node, automationActive); + syncNodeWidget(node, "face_swap_enabled", automationActive); + // Force la taille immédiatement (pas de latence au premier clic) + const newSize = node.computeSize(); + node.size[0] = Math.max(node.size[0], newSize[0]); + node.size[1] = newSize[1]; + app.graph.setDirtyCanvas(true, true); + }); + // ── Breast Refiner toggle ───────────────────────────────────────────── + brBtn.addEventListener("click", () => { + breastRefinerActive = !breastRefinerActive; + setToggleVisual(brBtn, breastRefinerActive, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", breastRefinerActive); + app.graph.setDirtyCanvas(true); + }); + // ── Low Neck toggle ─────────────────────────────────────────────────── + lnBtn.addEventListener("click", () => { + lowNeckActive = !lowNeckActive; + setToggleVisual(lnBtn, lowNeckActive, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", lowNeckActive); + app.graph.setDirtyCanvas(true); + }); + // ── Add DOM widget to node ──────────────────────────────────────────── + const domWidget = node.addDOMWidget("nb_faceswap_automation", "automation_div", container, { + serialize: false, + hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + // ── Restaure l'état sauvegardé dans le workflow ─────────────────────── + // Le DOM démarre à OFF par défaut ; on le réaligne sur les widgets Python + // pour que l'état visuel corresponde toujours à ce qui sera exécuté. + const _savedFS = getWidget(node, "face_swap_enabled")?.value === true; + if (_savedFS) { + automationActive = true; + _blockH = FS_HEIGHT_ON; + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + setToggleVisual(toggleBtn, true, FS_ON_STYLE); + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + applyAutomationState(node, true); + } + // Breast Refiner et Low Neck : toujours OFF au démarrage. + // On réinitialise le widget Python même si le workflow les avait sauvegardés + // à true, pour éviter qu'ils se réactivent silencieusement entre sessions. + syncNodeWidget(node, "breast_refiner_enabled", false); + syncNodeWidget(node, "low_neck_enabled", false); + // breastRefinerActive et lowNeckActive restent false, boutons restent OFF. + // Masque les widgets Python cachés (IMMÉDIATEMENT, pas en setTimeout, pour + // éviter que le node soit dessiné grand puis rétréci juste après). + const HIDDEN_PY_WIDGETS = [ + "face_swap_enabled", "breast_refiner_enabled", "low_neck_enabled", + "face_expression", "video_mode_enabled", + ]; + for (const name of HIDDEN_PY_WIDGETS) { + const w = getWidget(node, name); + if (!w) continue; + w._fsOrigComputeSize = w.computeSize; + w.computeSize = () => [0, -4]; + w.hidden = true; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + } + app.graph.setDirtyCanvas(true, true); +} +// ─── Preset panel (10 slots, mode-aware, avec champ nom) ────────────────── +function buildPresetUI(node) { + const NUM_PRESETS = 10; + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #37474f; + border-radius: 9px; + padding: 8px 10px 10px 10px; + background: linear-gradient(135deg, + rgba(55,71,79,0.14) 0%, + rgba(96,125,139,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + `; + forwardWheelToCanvas(container); + const titleEl = document.createElement("div"); + titleEl.textContent = "💾 PRESETS"; + titleEl.style.cssText = ` + font-weight: 700; font-size: 11.5px; color: #90a4ae; + letter-spacing: 2px; text-align: center; + margin-bottom: 7px; user-select: none; + `; + container.appendChild(titleEl); + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #37474f 40%, #37474f 60%, transparent); + opacity: 0.55; margin-bottom: 7px; + `; + container.appendChild(sep); + const list = document.createElement("div"); + list.style.cssText = "display: flex; flex-direction: column; gap: 4px;"; + container.appendChild(list); + const slotRows = {}; + const slotInputs = {}; + function markSlotFilled(n, filled, name) { + const row = slotRows[n]; + const input = slotInputs[n]; + if (!row) return; + row.style.border = filled ? "1px solid rgba(79,195,247,0.3)" : "1px solid #2a2a2a"; + row.style.background = filled ? "rgba(79,195,247,0.04)" : "#1a1a1a"; + if (input && name !== undefined) input.value = name || ""; + } + function buildSlot(n) { + const row = document.createElement("div"); + row.style.cssText = ` + display: flex; align-items: center; gap: 4px; + padding: 3px 5px; border-radius: 6px; + border: 1px solid #2a2a2a; background: #1a1a1a; + transition: border 0.2s, background 0.2s; + `; + slotRows[n] = row; + const label = document.createElement("span"); + label.textContent = `${n < 10 ? " " : ""}${n}`; + label.style.cssText = ` + font-size: 9.5px; color: #555; min-width: 14px; + user-select: none; font-weight: 700; font-variant-numeric: tabular-nums; + `; + const nameInput = document.createElement("input"); + nameInput.type = "text"; + nameInput.placeholder = `preset ${n}`; + nameInput.style.cssText = ` + flex: 1; min-width: 0; + background: #111; border: 1px solid #333; border-radius: 4px; + color: #aaa; font-size: 9.5px; padding: 2px 5px; + outline: none; font-family: 'Segoe UI', Arial, sans-serif; + `; + nameInput.addEventListener("focus", () => nameInput.style.borderColor = "#546e7a"); + nameInput.addEventListener("blur", () => nameInput.style.borderColor = "#333"); + nameInput.addEventListener("keydown", e => e.stopPropagation()); + slotInputs[n] = nameInput; + const btnBase = ` + padding: 2px 8px; border-radius: 4px; font-size: 9px; + font-weight: 700; cursor: pointer; white-space: nowrap; + transition: all 0.15s ease; letter-spacing: 0.4px; + `; + const saveBtn = document.createElement("button"); + saveBtn.textContent = "SAVE"; + saveBtn.title = `Sauvegarder dans le slot ${n}`; + saveBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + const loadBtn = document.createElement("button"); + loadBtn.textContent = "LOAD"; + loadBtn.title = `Charger le slot ${n}`; + loadBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + row.appendChild(label); + row.appendChild(nameInput); + row.appendChild(saveBtn); + row.appendChild(loadBtn); + list.appendChild(row); + saveBtn.addEventListener("click", async () => { + const params = { preset_name: nameInput.value.trim() }; + for (const w of node.widgets || []) { + if (w.name && w.value !== undefined + && w.type !== "button" && w.type !== "dom_widget" + && !w.name.startsWith("nb_")) { + params[w.name] = w.value; + } + } + try { + const res = await fetch("/nb_aio/save_preset", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ slot: n, params }), + }); + const data = await res.json(); + if (data.success) { + markSlotFilled(n, true, params.preset_name); + saveBtn.style.cssText = btnBase + "border:1px solid #00c853; background:#1b5e20; color:#69f0ae;"; + setTimeout(() => { + saveBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + } + } catch (e) { console.error("[NB Presets] Save error:", e); } + }); + loadBtn.addEventListener("click", async () => { + try { + const res = await fetch("/nb_aio/load_presets"); + const data = await res.json(); + if (!data.success) return; + const preset = data.presets?.[String(n)]; + if (!preset) return; + const isVideo = preset.video_mode_enabled === true; + if (isVideo && !node._nbIsVideoMode) { + node._modeToggleAPI?.activateVideoMode(); + } else if (!isVideo && node._nbIsVideoMode) { + node._modeToggleAPI?.activateImageMode(); + } + if (preset.preset_name !== undefined) { + nameInput.value = preset.preset_name || ""; + } + markSlotFilled(n, true, preset.preset_name); + const SKIP = new Set(["video_mode_enabled", "preset_name"]); + for (const [key, value] of Object.entries(preset)) { + if (SKIP.has(key)) continue; + syncNodeWidget(node, key, value); + } + loadBtn.style.cssText = btnBase + "border:1px solid #2962ff; background:#0d47a1; color:#82b1ff;"; + setTimeout(() => { + loadBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + app.graph.setDirtyCanvas(true, true); + } catch (e) { console.error("[NB Presets] Load error:", e); } + }); + } + for (let i = 1; i <= NUM_PRESETS; i++) buildSlot(i); + const PANEL_H = 368; + const domWidget = node.addDOMWidget("nb_presets_ui", "presets_div", container, { + serialize: false, hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, PANEL_H]; + fetch("/nb_aio/load_presets") + .then(r => r.json()) + .then(data => { + if (!data.success) return; + for (let i = 1; i <= NUM_PRESETS; i++) { + const p = data.presets?.[String(i)]; + if (p) markSlotFilled(i, true, p.preset_name); + } + }) + .catch(() => {}); +} +// ─── Prompt widget colour coding ────────────────────────────────────────── +function stylePromptWidgets(node) { + setTimeout(() => { + const pos = getWidget(node, "prompt"); + if (pos?.inputEl) { + pos.inputEl.style.borderLeft = "3px solid #00c853"; + pos.inputEl.style.paddingLeft = "6px"; + pos.inputEl.style.borderRadius = "3px"; + } + const neg = getWidget(node, "negative_prompt"); + if (neg?.inputEl) { + neg.inputEl.style.borderLeft = "3px solid #e53935"; + neg.inputEl.style.paddingLeft = "6px"; + neg.inputEl.style.borderRadius = "3px"; + } + }, 200); +} +// ─── Extension registration ─────────────────────────────────────────────── +app.registerExtension({ + name: "NanoBananaAIO.FaceSwap", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "NanoBananaAIO") return; + const onCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onCreated?.apply(this, arguments); + const node = this; + stylePromptWidgets(node); + // Mode toggle en premier (synchrone) — place le widget tout en haut + buildModeToggle(node); + setTimeout(() => setupKlingAspectRatioSync(node), 500); + setTimeout(() => setupKlingDurationSync(node), 500); + setTimeout(() => setupProviderBatchSync(node), 500); + setTimeout(() => setupGPT2Sync(node), 500); + setTimeout(() => setupVideoResolutionSync(node), 500); + setTimeout(() => buildFaceSwapUI(node), 400); + setTimeout(() => buildPresetUI(node), 450); + // Nettoyage tardif des widgets preset hérités (autre JS) + setTimeout(() => { + if (!node.widgets) return; + const KEEP = new Set([ + "nb_faceswap_automation", "nb_presets_ui", "nb_mode_toggle", + "face_expression", "face_swap_enabled", "breast_refiner_enabled", + "low_neck_enabled", "video_mode_enabled", + ]); + const isLegacy = (w) => { + if (!w.name) return false; + if (KEEP.has(w.name)) return false; + if (w.name.startsWith("nb_")) return false; + const n = w.name.toLowerCase(); + return ( + w.type === "button" || + n.includes("preset") || + n.includes("slot") + ); + }; + for (let i = node.widgets.length - 1; i >= 0; i--) { + const w = node.widgets[i]; + if (!isLegacy(w)) continue; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + node.widgets.splice(i, 1); + } + // Force-hide des widgets Python automation (canvas widgets LiteGraph) + for (const name of ["face_expression", "face_swap_enabled", + "breast_refiner_enabled", "low_neck_enabled", + "video_mode_enabled"]) { + const w = getWidget(node, name); + if (!w) continue; + w.hidden = true; + w.computeSize = () => [0, -4]; + if (w.inputEl) { try { w.inputEl.remove(); } catch (_) {} w.inputEl = null; } + if (w.element) { try { w.element.remove(); } catch (_) {} w.element = null; } + } + app.graph.setDirtyCanvas(true, true); + }, 1200); + }; + }, +}); \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260424_213134_gemini_prompt.py b/aiorbust-ofm-pack-main/_backups/20260424_213134_gemini_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..ad8b3044b7e6cf276651b0cb03dae2a74ee465b7 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260424_213134_gemini_prompt.py @@ -0,0 +1,942 @@ +""" +ComfyUI node — OFM Prompt Generator. +Uses Gemini LLM to analyze images and generate structured JSON prompts, +or allows custom freeform prompt generation. +""" + +import io +import base64 +import logging +import re +import os +import sys +import json +import subprocess + +import numpy as np +import requests +from PIL import Image + + + +_PROVIDERS = ["Gemini", "Grok", "Vertex"] + +_GEMINI_MODELS = [ + "gemini-2.5-pro", + "gemini-2.5-flash", + "gemini-2.0-flash", +] + +_GROK_MODELS = [ + # Vision-capable models (support image input) + "grok-4.20-0309-reasoning", + "grok-4.20-0309-non-reasoning", + "grok-4-1-fast-reasoning", + "grok-4-1-fast-non-reasoning", + "grok-2-vision-1212", + # Text-only models (no image input) + "grok-3", + "grok-3-fast", + "grok-3-mini", + "grok-3-mini-fast", +] + +_PROMPT_MODES = [ + "JSON Image Analysis", + "Style Transfer Prompt", + "Seedream Edit (2 face + 1 ref)", + "Seedream Edit (1 face + 1 ref)", + "Seedream Edit (2 face and body + 1 ref)", + "Seedream Edit (2 faces + 2 bodies + 1ref)", + "Custom Prompt", +] + +# ---------- Built-in JSON analysis prompt ---------- + +_JSON_ANALYSIS_PROMPT = r"""## Context & Goal +You are an expert visual analysis specialist with 15+ years of experience in digital art, photography, graphic design, and AI image generation. You excel at deconstructing visual elements and translating artistic styles into technical specifications. + +Your task: Analyze the uploaded image and return a comprehensive JSON profile for recreating the visual style. + +## Output Format +Return ONLY valid JSON. No explanations, no commentary, no markdown formatting. + +## Core JSON Schema + +{ +"metadata": { +"confidence_score": "high/medium/low - assessment of analysis accuracy", +"image_type": "photograph/digital art/illustration/graphic design/mixed media", +"primary_purpose": "marketing/editorial/social media/product/portrait/landscape/abstract" +}, +"composition": { +"rule_applied": "rule of thirds/golden ratio/center composition/symmetry/asymmetry", +"aspect_ratio": "width:height ratio or format description", +"layout": "grid/single subject/multi-element/layered", +"focal_points": [ +"Primary focal point location and element", +"Secondary focal point if present" +], +"visual_hierarchy": "Description of how eye moves through the image", +"balance": "symmetric/asymmetric/radial - with description" +}, +"color_profile": { +"dominant_colors": [ +{ +"color": "Specific color name", +"hex": "#000000", +"percentage": "approximate percentage of image", +"role": "background/accent/primary subject" +} +], +"color_palette": "complementary/analogous/triadic/monochromatic/split-complementary", +"temperature": "warm/cool/neutral - overall feeling", +"saturation": "highly saturated/moderate/desaturated/black and white", +"contrast": "high contrast/medium contrast/low contrast/soft" +}, +"lighting": { +"type": "natural window/artificial/mixed/studio/practical lights", +"source_count": "single source/multiple sources - number and placement", +"direction": "front/45-degree side/90-degree side/back/top/bottom/diffused from above", +"directionality": "highly directional/moderately directional/diffused/omni-directional", +"quality": "hard light/soft light/dramatic/even/gradient/sculpted", +"intensity": "bright/moderate/low/moody/high-key/low-key", +"contrast_ratio": "high contrast (dramatic shadows)/medium contrast/low contrast (flat)", +"mood": "cheerful/dramatic/mysterious/calm/energetic/professional/casual", +"shadows": { +"type": "harsh defined edges/soft gradual edges/minimal/dramatic/absent", +"density": "deep black/gray/transparent/faint", +"placement": "under subject/on wall/from objects/cast patterns", +"length": "short/medium/long - shadow projection distance" +}, +"highlights": { +"treatment": "blown out/preserved/subtle/dramatic/specular", +"placement": "on face/hair/clothing/background - where light hits strongest" +}, +"ambient_fill": "present/absent - secondary fill light reducing shadows", +"light_temperature": "warm (golden)/neutral/cool (blue) - color cast" +}, +"technical_specs": { +"medium": "digital photography/3D render/digital painting/vector/photo manipulation/mixed", +"style": "realistic/hyperrealistic/stylized/minimalist/maximalist/abstract/surreal", +"texture": "smooth/grainy/sharp/soft/painterly/glossy/matte", +"sharpness": "tack sharp/slightly soft/deliberately soft/bokeh effect", +"grain": "none/film grain/digital noise/intentional grain - level", +"depth_of_field": "shallow/medium/deep - with subject isolation description", +"perspective": "straight on/low angle/high angle/dutch angle/isometric/one-point/two-point" +}, +"artistic_elements": { +"genre": "portrait/landscape/abstract/conceptual/commercial/editorial/street/fine art", +"influences": [ +"Identified artistic movement, photographer, or style influence" +], +"mood": "energetic/calm/dramatic/playful/sophisticated/raw/polished", +"atmosphere": "Description of overall feeling and emotional impact", +"visual_style": "clean/cluttered/minimal/busy/organic/geometric/fluid/structured" +}, +"typography": { +"present": "true or false", +"fonts": [ +{ +"type": "sans-serif/serif/script/display/handwritten", +"weight": "thin/light/regular/medium/bold/black", +"characteristics": "modern/vintage/playful/serious/technical" +} +], +"placement": "overlay/integrated/border/corner - with strategic description", +"integration": "subtle/prominent/dominant/background" +}, +"subject_analysis": { +"primary_subject": "Main subject description - DO NOT describe face structure, hair, skin tone, or any identity features", +"positioning": "center/left/right/top/bottom/rule of thirds placement", +"scale": "close-up/medium/full/environmental/macro", +"interaction": "isolated/interacting with environment/multiple subjects", +"facial_expression": { +"mouth": "closed smile/open smile/slight smile/neutral/serious/pursed - exact mouth position", +"smile_intensity": "no smile/subtle/moderate/broad/wide - degree of smile", +"eyes": "direct gaze/looking away/squinting/wide/relaxed/intense - eye expression", +"eyebrows": "raised/neutral/furrowed/relaxed - brow position", +"overall_emotion": "happy/content/serious/playful/confident/approachable/guarded/warm/cold", +"authenticity": "genuine/posed/candid/formal/natural" +}, +"hands_and_gestures": { +"left_hand": "Exact position and gesture - touching face/holding object/resting on surface/in pocket/behind back/clasped/visible or not visible", +"right_hand": "Exact position and gesture - touching face/holding object/resting on surface/in pocket/behind back/clasped/visible or not visible", +"finger_positions": "Specific details: pointing/peace sign/thumbs up/relaxed/gripping/spread/interlaced/curled", +"finger_interlacing": "if hands clasped: natural loose interlacing/tight formal interlacing/fingers overlapping/thumbs position", +"hand_tension": "relaxed/tense/natural/posed/rigid - muscle tension observable", +"interaction": "What hands are doing: holding phone/touching hair/on hip/crossed/clasped at waist/clasped at chest/gesturing", +"naturalness": "organic casual gesture/deliberately posed/caught mid-motion/static formal pose" +}, +"body_positioning": { +"posture": "standing/sitting/leaning/lying - exact position", +"angle": "facing camera/45 degree turn/profile/back to camera", +"weight_distribution": "leaning left/right/centered/shifted", +"shoulders": "level/tilted/rotated/hunched/back" +} +}, +"background": { +"setting_type": "indoor/outdoor/studio/natural environment - specific location", +"spatial_depth": "shallow/medium/deep - layers description", +"elements_detailed": [ +{ +"item": "Specific object name (if plant: species like monstera/pothos/bird of paradise/fern)", +"position": "left/right/center/top/bottom - exact placement with quadrant", +"distance": "foreground/midground/background", +"size": "dominant/medium/small - relative scale and proportion", +"condition": "new/worn/vintage/pristine/wilted/thriving - state description", +"specific_features": "For plants: flower color, leaf pattern, pot type; For objects: brand, wear, details" +} +], +"wall_surface": { +"material": "painted drywall/concrete/brick/wood paneling/tile/wallpaper/plaster - exact base material", +"surface_treatment": "smooth paint/textured paint/raw concrete/polished concrete/exposed brick/finished/unfinished", +"texture": "perfectly smooth/slightly textured/rough/patterned/brushed - tactile quality", +"finish": "matte/satin/glossy/flat - sheen level", +"color": "Specific color with undertones (e.g., warm gray, cool blue-gray, off-white)", +"color_variation": "uniform/gradient/patchy/streaked - color consistency", +"features": "clean/water stains/vertical streaks/horizontal marks/cracks/patches/fixtures/artwork/scuffs - ALL observable surface details", +"wear_indicators": "pristine/aged/weathered/industrial/residential - condition and style" +}, +"floor_surface": { +"material": "wood/tile/carpet/concrete/grass - exact type", +"color": "Specific color", +"pattern": "solid/checkered/striped/herringbone - if present" +}, +"objects_catalog": "List every visible object with position: furniture pieces, decorative items, functional objects, natural elements", +"background_treatment": "blurred/sharp/minimal/detailed/gradient/textured" +}, +"generation_parameters": { +"prompts": [ +"Detailed technical prompt for recreating this style", +"Alternative angle or variation prompt" +], +"keywords": [ +"keyword1", +"keyword2", +"keyword3", +"keyword4", +"keyword5" +], +"technical_settings": "Recommended camera/render settings description for recreation", +"post_processing": "Color grading, filters, or editing techniques applied" +} +} + +## Analysis Rules + +### Composition Analysis +- Identify grid systems, alignment, and spatial relationships +- Note use of negative space and breathing room +- Describe visual flow and eye movement path +- Identify focal points using color, contrast, size, or placement +- Assess balance between elements + +### Color Analysis +- Extract dominant colors with approximate hex values +- Identify color relationships (complementary, analogous, etc.) +- Assess temperature bias (warm vs cool) +- Note saturation levels and contrast intensity +- Describe how color creates mood and directs attention + +### Lighting Assessment +- Determine light source type, direction, and quality +- Analyze shadow characteristics and depth +- Assess highlight preservation or blown-out areas +- Describe overall lighting mood and emotional impact +- Note light's role in creating dimension and form + +### Technical Evaluation +- Identify creation medium and technique +- Assess texture, sharpness, and grain characteristics +- Evaluate depth of field and focus points +- Analyze perspective and viewpoint +- Note any technical limitations or intentional choices + +### Artistic Context +- Identify genre and artistic influences +- Assess mood, atmosphere, and emotional tone +- Describe visual style (minimal, maximalist, etc.) +- Note any cultural or temporal references +- Evaluate overall aesthetic cohesion + +### Typography (if present) +- Identify font styles and weights +- Assess placement and integration strategy +- Evaluate readability and hierarchy +- Describe relationship to other visual elements + +### Subject Treatment +- **CRITICAL EXCLUSION — Face & Hair**: Do NOT describe facial features, facial expression, hair color, hair style, hair length, hair texture, skin tone, eye color, or any identity-defining features. These will be provided by separate face reference images. Skip these entirely. +- **Hand & Gesture Analysis (CRITICAL)**: + - Describe EACH hand separately with exact position + - Note if hands are visible or hidden (in pockets, behind back, out of frame) + - Document specific finger positions and shapes + - For clasped hands: describe interlacing style (natural loose vs formal tight), thumb positions, finger overlap patterns + - Assess hand tension: relaxed vs tense, organic vs posed + - Describe what hands are interacting with (phone, face, object, clothing, each other) + - Note natural vs posed quality of gesture + - Specify pressure/contact points (lightly touching vs gripping) + - Evaluate overall naturalness: organic casual vs deliberately posed +- **Background Elements (CRITICAL)**: + - Catalog EVERY visible object with exact position and quadrant placement + - For plants: identify species (monstera, pothos, bird of paradise, fern, etc.) + - Describe spatial relationships between objects and their depth layers + - **Wall analysis is CRITICAL**: + - Distinguish between painted drywall vs concrete vs brick vs other materials + - Note surface treatment: smooth paint vs textured vs raw vs polished + - Document finish: matte vs glossy vs satin + - Identify any surface features: water stains, streaks, cracks, patches, wear + - Assess condition: pristine residential vs industrial weathered vs aged + - Document floor type, color, pattern + - Specify distance/depth layer for each element + - Note condition and state of objects (new/worn/vintage/thriving/wilted) + - Describe any text, artwork, or decorative elements + - Include architectural features (windows, doors, molding, fixtures, frames) +- **Lighting Analysis (CRITICAL)**: + - Distinguish between dramatic directional lighting vs flat even lighting + - Assess directionality: highly directional (strong shadows) vs diffused (soft minimal shadows) + - Document shadow characteristics: harsh defined edges vs soft gradual edges vs minimal + - Note contrast ratio: high contrast (dramatic) vs low contrast (flat) + - Identify if ambient fill light is present reducing shadow depth + - Describe how light sculpts the subject vs evenly illuminates + - Document cast shadows from objects (like plants) on walls + - Note shadow density: deep black vs gray vs faint +- Analyze primary subject and positioning (but NOT face, hair, or identity features) +- Assess scale and framing choices +- Describe subject-background relationship +- Note any secondary subjects or supporting elements + +### Generation Parameters +- Create actionable technical prompts for recreation +- Extract relevant keywords for searchability +- Recommend technical settings for similar results +- Describe post-processing techniques applied + +## Output Requirements +- **Format**: Valid JSON only +- **No markdown**: No ```json``` blocks, no backticks +- **No commentary**: No explanatory text before/after JSON +- **No instructions**: No "Here is your analysis" or "Copy this" +- **Clean structure**: Properly formatted, parseable JSON +- **Single object**: Return one complete JSON analysis object +- **Comprehensive**: All sections must be populated with detailed analysis +- **Specific**: Use precise technical terminology, not vague descriptions +- **Actionable**: Generation parameters must be detailed enough for recreation + +## Processing Logic +1. Analyze the provided image comprehensively across all categories +2. Extract technical specifications and artistic elements +3. Generate recreation prompts and parameters +4. Output single, complete JSON object + +## Quality Standards +- **Confidence score**: Honest assessment of analysis certainty +- **Hex codes**: Approximate but reasonable color values +- **Specific descriptions**: Avoid generic terms like "nice" or "good" +- **Technical accuracy**: Use correct terminology for medium and technique +- **Completeness**: Every JSON field must contain meaningful analysis +- **Actionability**: Prompts and keywords must be specific enough to recreate style + +### CRITICAL Accuracy Requirements: + +**CRITICAL EXCLUSION — Face Structure & Hair:** +- Do NOT include any hair fields (length, cut, texture, styling, part, volume, details, color) +- Do NOT describe face structure, skin tone, eye color, hair color, or any identity-defining features +- These are controlled by separate face reference images and must be omitted entirely +- EXCEPTION: DO include facial_expression fields (mouth position, smile intensity, eye gaze, eyebrow position, emotion, authenticity) — expressions must be captured from the analyzed image + +**Hand & Gesture Description Must Include:** +- Position of BOTH hands (even if one is hidden) +- Exact finger configurations +- For clasped hands: interlacing pattern (loose/tight), thumb position, finger overlap +- Hand tension assessment (relaxed vs tense) +- What hands are interacting with +- Natural vs posed quality with specific evidence +- Contact points and pressure +- Overall gesture naturalness assessment + +**Background Description Must Include:** +- Every visible object cataloged with quadrant position +- Plant species identification (not just "plant") +- Wall material distinction (painted drywall vs concrete vs brick - THIS IS CRITICAL) +- Wall surface treatment (smooth paint vs raw concrete vs textured) +- Wall finish (matte vs glossy) and condition (pristine vs weathered vs industrial) +- Any surface features: water stains, vertical streaks, cracks, patches +- Floor materials with exact colors +- Spatial depth layers (foreground/mid/background) for each element +- Object conditions and states +- Architectural features +- Text or decorative elements + +**Lighting Description Must Include:** +- Directionality assessment (highly directional vs diffused) +- Contrast ratio (high/medium/low) +- Shadow characteristics: edge quality (harsh vs soft), density (deep vs faint), placement +- Cast shadows from objects onto walls +- Presence or absence of ambient fill light +- Whether lighting is dramatic and sculpting vs flat and even +- This distinction is CRITICAL for recreation accuracy + +**Facial Expression (INCLUDE — this is the exception):** +- Exact mouth position (closed smile/slight smile/neutral/serious) +- Smile intensity quantification +- Eye gaze direction and expression +- Eyebrow position +- Overall emotional tone (warm vs neutral vs serious) +- Genuine vs posed quality assessment +- NOTE: Describe the EXPRESSION only, NOT the facial structure (no face shape, no eye color, no skin tone)""" + + +# ---------- Built-in style transfer prompt ---------- + +_STYLE_TRANSFER_PROMPT = r"""You are an expert image editing prompt engineer. Analyze this reference image and extract ALL visual characteristics that should be transferred to another image. Then generate a concise, actionable editing instruction. + +Extract and describe these elements: + +**Subject Appearance:** +- **Clothing**: exact garments, colors, fabrics, fit, style (e.g., "oversized cream knit sweater with a V-neck", "black leather jacket unzipped over a white graphic tee") +- **Pose**: exact body position, angle, weight distribution, hand placement, arm positions, lean direction +- **Facial expression**: exact mouth position (smile type/intensity), eye gaze direction, eyebrow position, overall emotional tone +- **Hair styling**: current style, part, volume, texture state + +**Visual Style:** +- **Lighting**: direction, quality (hard/soft), intensity, color temperature, shadow characteristics +- **Color grading**: overall palette, temperature, saturation, contrast, any color tint or cast +- **Mood/atmosphere**: emotional tone, ambiance +- **Texture/grain**: film grain, noise, smoothness, sharpness +- **Depth of field**: bokeh style, focus +- **Post-processing**: filters, vignetting, bloom, haze, matte look +- **Background**: setting type, colors, blur level, key elements + +Output ONLY the editing instruction as a single paragraph. No explanations, no bullet points, no headers, no markdown. + +Format your output exactly like this example: +"Edit this image so the subject is wearing an oversized cream knit sweater with a V-neck, posed leaning slightly against a wall with their left hand in their pocket and right hand touching their hair, with a relaxed genuine slight smile and direct eye contact, warm golden hour lighting from the left side with soft diffused shadows, desaturated film look with lifted blacks and muted earth tones, subtle film grain, shallow depth of field with a blurred neutral-toned indoor background." + +Be extremely specific about clothing, pose, and expression. The output will be fed directly to an AI image editing model.""" + + +# ---------- Built-in Seedream Edit prompt ---------- + +_SEEDREAM_EDIT_PROMPT = r"""You are Gemini 2.5, an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. +Primary Directive: Your task is to analyze Reference Image 3 (a complete scene) and generate a single, comprehensive prompt for Seedream 4.5. This prompt will instruct the model on how to use a total of three reference images. +Critical Context (Non-negotiable): Seedream will always receive 3 reference images in this specific order: +Images 1 & 2: Provide the subject's complete face structure, facial features, and identity. +Image 3: The complete scene reference (this is the image you will be given to analyze). +Your analysis must focus exclusively on Image 3. Your generated prompt must correctly instruct Seedream on this specific 3-image workflow. +Your Generation Task: +You will be given Image 3. +You will analyze Image 3 ONLY. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. +Mandatory Output Format (Strict Template): +Use the first two reference images for the subject's complete face, features, and identity. Use reference image 3 as the complete reference for all other elements: clothing, pose, action, body type, scene composition, background environment, lighting, and overall atmosphere. +Subject details: [Describe the subject's clothing in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the features.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +_SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT = r"""You are an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. + +Primary Directive: Your task is to analyze all 3 provided images and generate a single, comprehensive prompt for Seedream 4.5. + +Critical Context (Non-negotiable): Seedream will always receive 3 reference images in this specific order: +Images 1 & 2: Provide the subject's complete face structure, facial features, identity, AND body type, body shape, body proportions, skin tone, and any body-specific details such as tattoos, scars, or markings. The output body MUST match these images. +Image 3: The complete scene reference. Provides ONLY the clothing, pose, action, scene composition, background environment, lighting, and overall atmosphere. The body type in Image 3 should be IGNORED — the body must come from Images 1 & 2. + +Your Generation Task: +You will be given all 3 images. +You will analyze Images 1 & 2 for the subject's body proportions and physical build. +You will analyze Image 3 for the scene, clothing, pose, lighting, and atmosphere. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. + +Mandatory Output Format (Strict Template): +Use the first two reference images for the subject's complete face, features, identity, body type, body shape, proportions, skin tone, and any body-specific details such as tattoos or markings. Use reference image 3 as the reference for clothing, pose, action, scene composition, background environment, lighting, and overall atmosphere ONLY — do NOT use image 3 for body type or physique. +Body proportions (from images 1 & 2): [Describe the subject's body proportions in explicit detail as observed in images 1 & 2. Include: overall build (e.g., slim, athletic, curvy, petite, voluptuous), bust/chest size (e.g., small, medium, large, very large), waist (e.g., narrow, thin, wide), hip and butt size (e.g., small, round, wide, large), leg shape (e.g., long, toned, thick), shoulder width, and any other distinctive body features. Be specific and direct — these proportions MUST be preserved in the output regardless of what Image 3's body looks like.] +Subject details: [Describe the subject's clothing from Image 3 in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose from Image 3: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the facial features.] [The body wearing these clothes must match images 1 & 2's body proportions exactly. Any tattoos, scars, or markings from images 1 & 2 must be visible on exposed skin and must not appear on top of clothing.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +# ---------- Built-in Seedream Edit (1 face + 1 ref) prompt ---------- + +_SEEDREAM_EDIT_1FACE_PROMPT = r"""You are Gemini 2.5, an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. + +Primary Directive: Your task is to analyze Reference Image 2 (a complete scene) and generate a single, comprehensive prompt for Seedream 4.5. This prompt will instruct the model on how to use a total of two reference images. + +Critical Context (Non-negotiable): Seedream will always receive 2 reference images in this specific order: +Image 1: Provides the subject's complete face structure, facial features, and identity. +Image 2: The complete scene reference (this is the image you will be given to analyze). + +Your analysis must focus exclusively on Image 2. Your generated prompt must correctly instruct Seedream on this specific 2-image workflow. + +Your Generation Task: +You will be given Image 2. +You will analyze Image 2 ONLY. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. + +Mandatory Output Format (Strict Template): +Use reference image 1 for the subject's complete face, features, and identity. Use reference image 2 as the complete reference for all other elements: clothing, pose, action, body type, scene composition, background environment, lighting, and overall atmosphere. +Subject details: [Describe the subject's clothing in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the features.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +_SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT = r"""You are an expert at creating complete image generation prompts for Seedream 4.0 AI model. + +IMPORTANT CONTEXT: +- Seedream will receive 5 reference images in this order: + 1. Images 1-2: Face structure references + 2. Images 3-4: Body type and physique references + 3. Image 5: THIS image - complete scene reference +- You are analyzing image 5 ONLY +- Your output must be a COMPLETE prompt for Seedream + +YOUR TASK: +Analyze this image and create a complete Seedream prompt that instructs the AI how to use all references and describes everything visible in THIS image. + +OUTPUT FORMAT (mandatory structure): +"Use the first two reference images for the face structure. Use reference images 3-4 for the body type and physique. Use reference image 5 as the complete reference for clothing, pose, action, scene composition, background environment, lighting setup, and overall atmosphere. + +Subject details: [Describe the person's clothing in complete detail - every garment, accessories, jewelry, shoes, specific details like patterns, textures, colors, cuts, styles]. [Describe the exact pose - standing, sitting, body position, arm placement, leg position]. [Describe what the person is doing - their action, gesture, body language, facial expression like smiling/serious but WITHOUT describing facial features]. + +The scene: [describe location type and setting]. The environment features [describe architectural elements, furniture, props, and background in detail]. The setting is [indoor/outdoor details with spatial relationships]. + +Lighting: [describe light source, direction, quality, shadows, time of day, color temperature in technical detail]. + +Camera: [describe perspective, depth of field, focal distance, composition. For camera angle: default to 'eye-level' unless the angle is clearly extreme. If the camera is only slightly below eye level, describe it as 'approximately eye-level with a very subtle upward perspective.' If slightly above, use 'approximately eye-level, tilted marginally downward.' Always understate the angle by one level to compensate for Seedream's tendency to exaggerate]. + +Atmosphere: [describe mood, ambiance, weather if applicable, environmental effects]. + +Colors and textures: [describe dominant colors throughout the scene, materials, surface properties, color palette]. + +Technical quality: [high-resolution, sharp focus, professional photography, etc.]." + +CRITICAL RULES: +- DO describe: clothing (every detail), pose, action, body language, gesture, expression type (smile/serious) +- NEVER describe: hair color, hair style, eye color, facial features, skin tone, ethnic features +- Use "this person", "the subject" when referring to the individual +- Be extremely detailed about clothing and accessories +- Be precise about pose and body position +- Focus on EVERYTHING visible except facial/hair features +- CAMERA ANGLE DAMPENING: Seedream heavily amplifies camera angle descriptions. Always understate angles by one full level. Near eye-level → "eye-level." Slightly low → "approximately eye-level with a very subtle upward perspective." Moderately low → "slightly below eye-level." Only use "low angle" if the camera is clearly at knee height or below. Same rule applies upward. +- BANNED CAMERA TERMS: Never use "low-angle shot," "worm's-eye view," "looking up at," "shot from below," or "high-angle shot" unless the source image shows a genuinely extreme perspective. Prefer neutral terms like "eye-level," "approximately eye-level," or "slightly adjusted." + +Output ONLY the formatted prompt, nothing else.""" + + +# ---------- Vertex AI helpers ---------- + +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + + +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + from google.oauth2 import service_account + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +# ---------- Serve prompts to frontend ---------- + +try: + from server import PromptServer + from aiohttp import web + + @PromptServer.instance.routes.get("/ofm_prompt_generator/get_prompts") + async def _get_prompts(request): + return web.json_response({ + "JSON Image Analysis": _JSON_ANALYSIS_PROMPT, + "Style Transfer Prompt": _STYLE_TRANSFER_PROMPT, + "Seedream Edit (2 face + 1 ref)": _SEEDREAM_EDIT_PROMPT, + "Seedream Edit (1 face + 1 ref)": _SEEDREAM_EDIT_1FACE_PROMPT, + "Seedream Edit (2 face and body + 1 ref)": _SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT, + "Seedream Edit (2 faces + 2 bodies + 1ref)": _SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT, + "Custom Prompt": "", + }) +except Exception: + logging.warning("OFM Prompt Generator: could not register API routes (server not available)") + + +# ---------- Image encoding helper ---------- + +def _image_tensor_to_parts(images): + """Convert ComfyUI IMAGE tensor [B, H, W, C] to Gemini inlineData parts.""" + parts = [] + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype(np.uint8) + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + parts.append({"inlineData": {"mimeType": "image/png", "data": b64}}) + return parts + + +def _strip_markdown_fences(text): + """Remove markdown code fences like ```json ... ``` from the response.""" + text = re.sub(r'^```\w*\s*\n?', '', text) + text = re.sub(r'\n?```\s*$', '', text) + return text.strip() + + +# ---------- Node ---------- + +class GeminiPromptNode: + """OFM Prompt Generator — analyze images or generate prompts with Gemini.""" + + # Cache last known good API keys to survive auto-queue serialization drops + _cached_gemini_key = "" + _cached_grok_key = "" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "mode": (_PROMPT_MODES, {"default": "JSON Image Analysis"}), + "provider": (_PROVIDERS, {"default": "Gemini"}), + "gemini_api_key": ("STRING", {"default": "", "multiline": False}), + "grok_api_key": ("STRING", {"default": "", "multiline": False}), + }, + "optional": { + "images": ("IMAGE",), + "custom_prompt": ("STRING", { + "default": "", + "multiline": True, + }), + "vertex_json_path": ("STRING", { + "default": "", + "multiline": False, + "tooltip": "Chemin vers le fichier JSON service account Vertex AI (provider Vertex uniquement)", + }), + "gemini_model": (_GEMINI_MODELS, {"default": "gemini-2.5-pro"}), + "grok_model": (_GROK_MODELS, {"default": "grok-4.20-0309-reasoning"}), + "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}), + "max_tokens": ("INT", {"default": 8192, "min": 64, "max": 65536, "step": 64}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFF}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("prompt",) + FUNCTION = "generate" + OUTPUT_NODE = True + CATEGORY = "utils" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def generate(self, mode, provider="Gemini", gemini_api_key="", grok_api_key="", + images=None, custom_prompt="", + vertex_json_path="", + gemini_model="gemini-2.5-pro", grok_model="grok-3", + temperature=1.0, max_tokens=8192, + seed=0): + # Update cache when keys are provided, fall back to cache when empty + if gemini_api_key.strip(): + GeminiPromptNode._cached_gemini_key = gemini_api_key.strip() + if grok_api_key.strip(): + GeminiPromptNode._cached_grok_key = grok_api_key.strip() + + gemini_api_key = gemini_api_key.strip() or GeminiPromptNode._cached_gemini_key + grok_api_key = grok_api_key.strip() or GeminiPromptNode._cached_grok_key + + logging.info("OFM Prompt Generator: provider=%s, gemini_key_len=%d, grok_key_len=%d", + provider, len(gemini_api_key), len(grok_api_key)) + if provider == "Gemini": + api_key = gemini_api_key + if not api_key: + raise RuntimeError("OFM Prompt Generator: Gemini API key is required.") + elif provider == "Vertex": + api_key = "" + if not vertex_json_path.strip(): + raise RuntimeError("OFM Prompt Generator: vertex_json_path est requis pour le provider Vertex.") + else: + api_key = grok_api_key + if not api_key: + raise RuntimeError("OFM Prompt Generator: Grok API key is required.") + + # Pick the prompt based on mode + if mode == "JSON Image Analysis": + instruction = _JSON_ANALYSIS_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: an image is required for JSON Image Analysis mode.") + elif mode == "Style Transfer Prompt": + instruction = _STYLE_TRANSFER_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image is required for Style Transfer Prompt mode.") + elif mode == "Seedream Edit (2 face + 1 ref)": + instruction = _SEEDREAM_EDIT_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 3 - the scene) is required for Seedream Edit mode.") + elif mode == "Seedream Edit (1 face + 1 ref)": + instruction = _SEEDREAM_EDIT_1FACE_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 2 - the scene) is required for Seedream Edit mode.") + elif mode == "Seedream Edit (2 face and body + 1 ref)": + instruction = _SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 3 - the scene) is required for Seedream Edit (2 face and body + 1 ref) mode.") + elif mode == "Seedream Edit (2 faces + 2 bodies + 1ref)": + instruction = _SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 5 - the scene) is required for Seedream Edit (2 faces + 2 bodies + 1ref) mode.") + else: + instruction = custom_prompt.strip() + if not instruction: + raise RuntimeError("OFM Prompt Generator: custom_prompt cannot be empty in Custom Prompt mode.") + + if provider == "Grok": + text = self._call_grok(api_key, grok_model, instruction, images, temperature, max_tokens) + elif provider == "Vertex": + text = self._call_vertex(vertex_json_path, gemini_model, instruction, images, temperature, max_tokens) + else: + text = self._call_gemini(api_key, gemini_model, instruction, images, temperature, max_tokens) + + text = _strip_markdown_fences(text) + + # Prepend face-preservation instruction for JSON Image Analysis mode + if mode == "JSON Image Analysis": + face_prefix = ( + "Generate a high-quality photograph using ONLY the face and skin tone from reference image 1. " + "Use reference image 2 as the visual reference for everything else: hair, clothing, pose, body positioning, " + "styling, lighting, composition, background, color palette, mood, and all other visual details. " + "The following JSON analysis is a detailed breakdown of reference image 2 — follow it precisely:\n" + ) + text = face_prefix + text + + active_model = grok_model if provider == "Grok" else gemini_model + logging.info("OFM Prompt Generator: generated %d chars with %s", len(text), active_model) + return {"ui": {"text": [text]}, "result": (text,)} + + def _call_gemini(self, api_key, model, instruction, images, temperature, max_tokens): + url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}" + + parts = [] + if images is not None: + parts.extend(_image_tensor_to_parts(images)) + parts.append({"text": instruction}) + + payload = { + "contents": [{"parts": parts}], + "generationConfig": { + "temperature": temperature, + "maxOutputTokens": max_tokens, + }, + } + + try: + resp = requests.post(url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=180) + resp.raise_for_status() + data = resp.json() + except requests.exceptions.HTTPError as e: + msg = f"OFM Prompt Generator API error: {e.response.status_code}" + try: + body = e.response.json() + if "error" in body: + msg += f" — {body['error']}" + except Exception: + msg += f" — {e.response.text[:200]}" + raise RuntimeError(msg) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"OFM Prompt Generator request error: {e!s}") + + text = _extract_text(data) + if not text: + raise RuntimeError(f"OFM Prompt Generator: no text in response. {_response_summary(data)}") + return text + + def _call_vertex(self, json_path, model, instruction, images, temperature, max_tokens): + from google import genai + from google.genai import types + + credentials, project_id = _load_vertex_credentials(json_path) + print(f"\U0001f310 [Vertex AI] Connexion \u2014 projet={project_id} | location=us-central1 | mod\u00e8le={model}") + + client = genai.Client( + vertexai=True, + project=project_id, + location="us-central1", + credentials=credentials, + ) + + contents = [] + if images is not None: + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype("uint8") + pil = Image.fromarray(img_np) + contents.append(pil) + contents.append(instruction) + + config = types.GenerateContentConfig( + temperature=temperature, + max_output_tokens=max_tokens, + ) + + try: + response = client.models.generate_content( + model=model, + contents=contents, + config=config, + ) + except Exception as e: + raise RuntimeError(f"OFM Prompt Generator (Vertex) erreur API : {e}") + + text = "" + try: + for part in response.candidates[0].content.parts: + if getattr(part, "thought", False): + continue + if hasattr(part, "text") and part.text: + text += part.text + except Exception: + pass + if not text: + try: + text = response.text or "" + except Exception: + pass + if not text: + raise RuntimeError("OFM Prompt Generator (Vertex) : aucun texte dans la r\u00e9ponse.") + return text.strip() + + def _call_grok(self, api_key, grok_model, instruction, images, temperature, max_tokens): + url = "https://api.x.ai/v1/chat/completions" + + # Build message content + content = [] + if images is not None: + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype("uint8") + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + content.append({ + "type": "image_url", + "image_url": {"url": f"data:image/png;base64,{b64}"}, + }) + content.append({"type": "text", "text": instruction}) + + payload = { + "model": grok_model, + "messages": [{"role": "user", "content": content}], + "temperature": temperature, + "max_completion_tokens": max_tokens, + } + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + } + + try: + resp = requests.post(url, json=payload, headers=headers, timeout=180) + resp.raise_for_status() + data = resp.json() + except requests.exceptions.HTTPError as e: + msg = f"OFM Prompt Generator (Grok) API error: {e.response.status_code}" + try: + body = e.response.json() + if "error" in body: + msg += f" \u2014 {body['error']}" + except Exception: + msg += f" \u2014 {e.response.text[:200]}" + raise RuntimeError(msg) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"OFM Prompt Generator (Grok) request error: {e!s}") + + choices = data.get("choices", []) + if not choices: + raise RuntimeError("OFM Prompt Generator (Grok): no choices in API response.") + text = choices[0].get("message", {}).get("content", "") + if not text: + raise RuntimeError("OFM Prompt Generator (Grok): empty response from API.") + return text + + +def _extract_text(data): + """Extract concatenated text from Gemini response, skipping thought parts.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + return None + parts = candidates[0].get("content", {}).get("parts") or [] + texts = [] + for part in parts: + if part.get("thought"): + continue + if "text" in part: + texts.append(part["text"]) + return "\n".join(texts).strip() if texts else None + except (KeyError, TypeError): + return None + + +def _response_summary(data): + """Summarize why the response had no usable text.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + block = data.get("promptFeedback", {}).get("blockReason", "") + if block: + return f"Prompt blocked: {block}" + return "No candidates returned." + reason = candidates[0].get("finishReason", "") + return f"finishReason={reason}" + except Exception: + return "" diff --git a/aiorbust-ofm-pack-main/_backups/20260424_214311_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260424_214311_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..580103cae433faa7fd87b3719d7ef8c4ee246b56 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260424_214311_nano_banana_aio.py @@ -0,0 +1,6366 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_path": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin complet vers le fichier JSON du service account.", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if not prompt or not prompt.strip(): + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_path = (vertex_json_path or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_path = vj_path, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + # ── Vertex n'accepte pas les requêtes simultanées ── + if provider == "VERTEX": + batch_size = 1 + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_path = vj_path, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_path: + return self._handle_error( + "❌ vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_path=vj_path, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_path=vj_path, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + ): + if not vertex_json_path: + return self._handle_error("❌ vertex_json_path manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, vertex_json_path, vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + vertex_json_path, vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, vertex_json_path, vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_path="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Automation] vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Video] vertex_json_path manquant pour le provider VERTEX." + ) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260425_195840_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260425_195840_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..a06535ce6c99fffe23177f594efe748b5974da01 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260425_195840_nano_banana_aio.py @@ -0,0 +1,6366 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_path": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin complet vers le fichier JSON du service account.", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_path = (vertex_json_path or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_path = vj_path, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + # ── Vertex n'accepte pas les requêtes simultanées ── + if provider == "VERTEX": + batch_size = 1 + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_path = vj_path, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_path: + return self._handle_error( + "❌ vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_path=vj_path, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_path=vj_path, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + ): + if not vertex_json_path: + return self._handle_error("❌ vertex_json_path manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, vertex_json_path, vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + vertex_json_path, vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, vertex_json_path, vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_path="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Automation] vertex_json_path manquant pour le provider VERTEX." + ) + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_path: + return self._handle_error( + "❌ [Video] vertex_json_path manquant pour le provider VERTEX." + ) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = vertex_json_path, + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260425_204322_nb_aio_faceswap.js b/aiorbust-ofm-pack-main/_backups/20260425_204322_nb_aio_faceswap.js new file mode 100644 index 0000000000000000000000000000000000000000..c6a2087b57d41a490f16cac0f32e7b315cb82dd7 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260425_204322_nb_aio_faceswap.js @@ -0,0 +1,1134 @@ +/** + * NanoBananaAIO — Automation Face Swap UI + Image/Video Mode Toggle + * Bloc visuel distinctif avec toggle ON/OFF, verrouillage des widgets, + * restriction du modèle à NBPro/NB2, et option Breast Refiner. + * + Toggle IMAGE / VIDEO avec support Veo 3 (Google & Vertex). + */ +import { app } from "../../scripts/app.js"; +// ─── Constantes mode vidéo ───────────────────────────────────────────────── +const VIDEO_MODELS = ["Veo 3.1 Lite", "Veo 3.1", "Veo 3.1 Fast", "Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control", "Seedance 2.0"]; +const IMAGE_MODELS_DEFAULT = ["Nano Banana Pro", "Nano Banana 2", "Seedream 4.5", "GPT Image 2.0"]; +const VIDEO_ASPECT_RATIOS = ["16:9", "9:16"]; +const IMAGE_ASPECT_RATIOS = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"]; +const VIDEO_RESOLUTIONS = ["480p", "720p", "1080p", "4K"]; +const KLING30_MODELS = ["Kling 3.0"]; +const IMAGE_RESOLUTIONS = ["1K", "2K", "4K"]; +const SEEDANCE_MODELS = ["Seedance 2.0"]; +// ─── Widgets verrouillés en mode automation ──────────────────────────────── +const LOCKABLE_WIDGETS = [ + "prompt", + "negative_prompt", + "use_search", + "system_instructions", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", +]; +const AUTOMATION_MODELS = ["Nano Banana Pro", "Nano Banana 2"]; +// ─── Helpers ─────────────────────────────────────────────────────────────── +function getWidget(node, name) { + return node.widgets?.find(w => w.name === name); +} +/** Synchronise un widget Python caché avec une valeur JS. */ +function syncNodeWidget(node, name, value) { + const w = getWidget(node, name); + if (w) { + w.value = value; + if (w.callback) w.callback(value); + } +} +/** Masque ou affiche un widget standard (computeSize trick). */ +function setWidgetVisible(node, widgetName, visible) { + const w = getWidget(node, widgetName); + if (!w) return; + if (visible) { + if (w._modeOrigComputeSize !== undefined) { + w.computeSize = w._modeOrigComputeSize; + delete w._modeOrigComputeSize; + } else { + delete w.computeSize; + } + w.disabled = false; + w.hidden = false; + } else { + if (w._modeOrigComputeSize === undefined) { + w._modeOrigComputeSize = w.computeSize; + } + w.computeSize = () => [0, -4]; + w.disabled = true; + w.hidden = true; + } + if (w.inputEl) w.inputEl.style.display = visible ? "" : "none"; + if (w.element) w.element.style.display = visible ? "" : "none"; +} +function setWidgetLocked(node, widgetName, locked) { + const w = getWidget(node, widgetName); + if (!w) return; + w.disabled = locked; + const applyStyle = (el) => { + if (!el || !el.style) return; + el.style.opacity = locked ? "0.3" : "1.0"; + el.style.pointerEvents = locked ? "none" : "auto"; + el.style.filter = locked ? "grayscale(60%)" : "none"; + }; + if (w.inputEl) { + w.inputEl.disabled = locked; + applyStyle(w.inputEl); + // Les widgets multiline (negative_prompt, system_instructions) sont + // wrappés dans un parent
; on applique aussi l'effet dessus. + applyStyle(w.inputEl.parentElement); + } + applyStyle(w.element); +} +/** + * Redirige les événements wheel du container DOM vers le canvas LiteGraph, + * pour que le zoom ComfyUI fonctionne même quand la souris survole un widget DOM. + */ +function forwardWheelToCanvas(el) { + el.addEventListener("wheel", (e) => { + e.preventDefault(); + e.stopPropagation(); + const canvas = app.canvas?.canvas; + if (!canvas) return; + canvas.dispatchEvent(new WheelEvent("wheel", { + bubbles: true, cancelable: true, view: window, + deltaX: e.deltaX, deltaY: e.deltaY, deltaZ: e.deltaZ, deltaMode: e.deltaMode, + clientX: e.clientX, clientY: e.clientY, screenX: e.screenX, screenY: e.screenY, + ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, metaKey: e.metaKey, + })); + }, { passive: false }); +} +/** + * Applique / retire l'état automation au node (verrouille les widgets + * et restreint la liste des modèles à NBPro/NB2). + */ +function applyAutomationState(node, enabled) { + const applyLocks = () => { + for (const name of LOCKABLE_WIDGETS) setWidgetLocked(node, name, enabled); + }; + // Passe immédiate, puis plusieurs passes différées pour rattraper les + // widgets multiline (negative_prompt, system_instructions) dont l'inputEl + // n'est parfois rattaché au DOM qu'après un ou deux frames. + applyLocks(); + requestAnimationFrame(applyLocks); + setTimeout(applyLocks, 100); + setTimeout(applyLocks, 400); + const modelWidget = getWidget(node, "model"); + if (!modelWidget) return; + if (enabled) { + if (modelWidget.options?.values) { + modelWidget.options.values = [...AUTOMATION_MODELS]; + } + if (!AUTOMATION_MODELS.includes(modelWidget.value)) { + modelWidget.value = "Nano Banana Pro"; + if (modelWidget.callback) modelWidget.callback("Nano Banana Pro"); + } + } else { + // Restaurer la liste selon le mode courant — Python déclare image+vidéo + // donc on ne peut plus se fier à _fsOrigValues comme source de vérité. + const correctModels = node._nbIsVideoMode ? VIDEO_MODELS : IMAGE_MODELS_DEFAULT; + if (modelWidget.options?.values) modelWidget.options.values = [...correctModels]; + // S'assurer que la valeur courante est dans la liste restaurée + if (!correctModels.includes(modelWidget.value)) { + modelWidget.value = correctModels[0]; + if (modelWidget.callback) modelWidget.callback(correctModels[0]); + } + } + modelWidget.disabled = false; + app.graph.setDirtyCanvas(true, true); +} +// ─── Sync aspect_ratio : grisé si Kling (any) + WAVESPEED en mode vidéo ──────── +// KLING_MODELS — conservé pour référence future, plus utilisé pour le verrouillage aspect_ratio +// (Kling supporte 16:9 et 9:16, les deux valeurs de VIDEO_ASPECT_RATIOS) +const KLING_MODELS = ["Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"]; +// GPT Image 2.0 — aspect ratios supportés (filtre automatique du dropdown) +const GPT2_ASPECT_RATIOS = ["1:1", "4:3", "3:4", "16:9", "9:16"]; +const GPT2_NEAREST_AR = { + "2:3": "9:16", "3:2": "16:9", "4:5": "3:4", "5:4": "4:3", "21:9": "16:9", +}; +function setupKlingAspectRatioSync(node) { + // Kling supporte 16:9 ET 9:16 — le dropdown est déjà restreint à VIDEO_ASPECT_RATIOS + // en mode vidéo, donc aucun verrouillage supplémentaire n'est nécessaire. + // La fonction reste en place pour compatibilité avec les appels existants. + node._nbSyncKlingAspectRatio = () => {}; +} +// ─── Contraintes de durée par modèle vidéo ──────────────────────────────────── +const DURATION_CONSTRAINTS = { + "Kling 2.6": { min: 5, max: 10, step: 5, tooltip: "⚠️ Kling 2.6 only supports 5s or 10s. Any other value will be rounded automatically." }, + "Kling 3.0": { min: 3, max: 15, step: 1, tooltip: "" }, + "Kling 3.0 Motion Control": { min: 3, max: 15, step: 1, tooltip: "ℹ️ Motion Control: output duration equals the reference video's duration." }, + "Seedance 2.0": { min: 4, max: 15, step: 1, tooltip: "⚠️ Seedance 2.0 : image-to-video uniquement." }, + _veo: { min: 4, max: 8, step: 1, tooltip: "" }, +}; +function getDurationConstraint(model) { + return DURATION_CONSTRAINTS[model] ?? DURATION_CONSTRAINTS._veo; +} + +// ─── Sync video_duration selon le modèle ────────────────────────────────────── +function setupKlingDurationSync(node) { + const modelWidget = getWidget(node, "model"); + const durationWidget = getWidget(node, "video_duration"); + if (!modelWidget || !durationWidget) return; + + /** Clamp une valeur dans [min, max] en respectant step. */ + const clampDuration = (v, { min, max, step }) => { + let clamped = Math.max(min, Math.min(max, parseInt(v) || min)); + // Pour step > 1 (ex. Kling 2.6 : step=5) : snap sur le multiple le plus proche + if (step > 1) { + const steps = Math.round((clamped - min) / step); + clamped = min + steps * step; + } + return Math.max(min, Math.min(max, clamped)); + }; + + /** Recalibre min/max/step et snappe la valeur si besoin. */ + const syncDuration = () => { + if (!node._nbIsVideoMode) return; + const c = getDurationConstraint(modelWidget.value); + if (durationWidget.options) { + durationWidget.options.min = c.min; + durationWidget.options.max = c.max; + durationWidget.options.step = c.step; + } + durationWidget.tooltip = c.tooltip; + const clamped = clampDuration(durationWidget.value, c); + if (durationWidget.value !== clamped) { + durationWidget.value = clamped; + if (durationWidget.callback) durationWidget.callback(clamped); + } + node.setDirtyCanvas(true); + }; + + node._nbSyncKlingDuration = syncDuration; + syncDuration(); + + // Hooker le changement de modèle → recalibrer la durée + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncDuration(); + }; +} +// ─── Sync batch_size selon provider et mode vidéo ───────────────────────── +function setupProviderBatchSync(node) { + const providerWidget = getWidget(node, "provider"); + const batchSizeWidget = getWidget(node, "batch_size"); + if (!providerWidget || !batchSizeWidget) return; + const syncBatchState = () => { + const isVertex = providerWidget.value === "VERTEX"; + const isVideo = node._nbIsVideoMode === true; + const shouldLock = isVertex || isVideo; + batchSizeWidget.disabled = shouldLock; + if (shouldLock) batchSizeWidget.value = 1; + node.setDirtyCanvas(true); + }; + // Expose pour que les fonctions activateVideoMode / activateImageMode + // puissent déclencher une resynchronisation sans passer par le callback + // du widget provider. + node._nbSyncBatchState = syncBatchState; + syncBatchState(); + const origCallback = providerWidget.callback; + providerWidget.callback = function (...args) { + if (origCallback) origCallback.apply(this, args); + syncBatchState(); + }; +} +// ─── Sync image_size (résolution) selon le modèle vidéo ───────────────────── +// Seedance 2.0 : 480p / 720p / 1080p (pas de 4K) +// Autres modèles vidéo : 720p / 1080p uniquement (pas de 480p) +function setupVideoResolutionSync(node) { + const modelWidget = getWidget(node, "model"); + const imgSizeWidget = getWidget(node, "image_size"); + if (!modelWidget || !imgSizeWidget) return; + + const syncResolution = () => { + if (!node._nbIsVideoMode) return; + const model = modelWidget.value; + const isSeedance = SEEDANCE_MODELS.includes(model); + const isKling30 = KLING30_MODELS.includes(model); + + let allowedRes, defaultRes; + if (isSeedance) { + allowedRes = ["480p", "720p", "1080p"]; + defaultRes = "720p"; + } else if (isKling30) { + allowedRes = ["720p", "1080p", "4K"]; + defaultRes = "1080p"; + } else { + allowedRes = ["720p", "1080p"]; + defaultRes = "1080p"; + } + + if (imgSizeWidget.options?.values) imgSizeWidget.options.values = [...allowedRes]; + if (!allowedRes.includes(imgSizeWidget.value)) { + imgSizeWidget.value = defaultRes; + if (imgSizeWidget.callback) imgSizeWidget.callback(defaultRes); + } + // Tooltip sur le widget modèle pour indiquer image-to-video uniquement + if (modelWidget.options) { + modelWidget.options.tooltip = isSeedance + ? "⚠️ Image-to-video uniquement" + : ""; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncVideoResolution = syncResolution; + + // Hooker le changement de modèle → recalibrer la résolution + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncResolution(); + }; +} +// ─── Sync aspect_ratio et gpt2_image_quality selon le modèle ───────────── +function setupGPT2Sync(node) { + const modelWidget = getWidget(node, "model"); + const arWidget = getWidget(node, "aspect_ratio"); + if (!modelWidget || !arWidget) return; + + /** Retourne le ratio le plus proche supporté par GPT2. */ + function nearestGPT2AR(value) { + if (GPT2_ASPECT_RATIOS.includes(value)) return value; + return GPT2_NEAREST_AR[value] || "1:1"; + } + + /** Applique ou retire le filtre GPT2 sur le dropdown aspect_ratio. */ + const syncAR = () => { + const isGPT2 = (modelWidget.value === "GPT Image 2.0"); + if (isGPT2) { + if (arWidget.options?.values) arWidget.options.values = [...GPT2_ASPECT_RATIOS]; + const snapped = nearestGPT2AR(arWidget.value); + if (arWidget.value !== snapped) { + arWidget.value = snapped; + if (arWidget.callback) arWidget.callback(snapped); + } + } else { + // Restaure la liste complète selon le mode courant + const fullList = node._nbIsVideoMode ? VIDEO_ASPECT_RATIOS : IMAGE_ASPECT_RATIOS; + if (arWidget.options?.values) arWidget.options.values = [...fullList]; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncGPT2AR = syncAR; + syncAR(); + + // Hooker le changement de modèle + const origCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origCb) origCb.apply(this, args); + syncAR(); + }; +} +// ─── Factorisation des styles des boutons ON/OFF ────────────────────────── +// Évite de dupliquer 8 lignes de style à chaque toggle (Face Swap, Breast +// Refiner, Low Neck). Chaque bouton a sa propre palette "ON". +const TOGGLE_OFF_CSS = { + text: "OFF", + background: "#3a3a3a", + color: "#888", + border: "1.5px solid #666", + boxShadow: "none", +}; +/** + * Applique l'état visuel ON/OFF à un bouton bascule. + * @param {HTMLButtonElement} btn + * @param {boolean} on + * @param {{bg:string, text?:string, border:string, glow:string}} onStyle + */ +function setToggleVisual(btn, on, onStyle) { + if (on) { + btn.textContent = onStyle.text || "ON"; + btn.style.background = onStyle.bg; + btn.style.color = "#fff"; + btn.style.border = `1.5px solid ${onStyle.border}`; + btn.style.boxShadow = `0 0 8px ${onStyle.glow}`; + } else { + btn.textContent = TOGGLE_OFF_CSS.text; + btn.style.background = TOGGLE_OFF_CSS.background; + btn.style.color = TOGGLE_OFF_CSS.color; + btn.style.border = TOGGLE_OFF_CSS.border; + btn.style.boxShadow = TOGGLE_OFF_CSS.boxShadow; + } +} +const FS_ON_STYLE = { bg: "#00c853", border: "#00e676", glow: "rgba(0,200,83,0.5)" }; +const BR_ON_STYLE = { bg: "#c2185b", border: "#f50057", glow: "rgba(245,0,87,0.4)" }; +const LN_ON_STYLE = { bg: "#6a1b9a", border: "#ab47bc", glow: "rgba(171,71,188,0.4)" }; +// CSS de base partagé par les 3 boutons ON/OFF (même taille, même rayon) +const TOGGLE_BTN_BASE_CSS = ` + padding: 4px 18px; + border-radius: 14px; + border: 1.5px solid #666; + background: #3a3a3a; + color: #888; + font-weight: 700; + font-size: 11px; + cursor: pointer; + min-width: 55px; + letter-spacing: 0.5px; + transition: all 0.2s ease; +`; +// ─── Image / Video mode toggle ──────────────────────────────────────────── +function buildModeToggle(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #1565c0; + border-radius: 9px; + padding: 8px 10px 11px 10px; + background: linear-gradient(135deg, + rgba(21,101,192,0.14) 0%, + rgba(79,195,247,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Titre ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ GENERATION MODE"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #4fc3f7; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(79,195,247,0.45); + margin-bottom: 7px; + user-select: none; + transition: color 0.25s, text-shadow 0.25s; + `; + container.appendChild(titleEl); + // ── Séparateur ──────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #1565c0 40%, #1565c0 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Boutons IMAGE / VIDÉO côte à côte ───────────────────────────────── + const btnRow = document.createElement("div"); + btnRow.style.cssText = "display:flex; gap:8px;"; + function makeChoiceBtn(label, active) { + const btn = document.createElement("button"); + btn.textContent = label; + btn.style.cssText = ` + flex: 1; + padding: 6px 4px; + border-radius: 8px; + border: 1.5px solid ${active ? "#4fc3f7" : "#444"}; + background: ${active ? "rgba(79,195,247,0.18)" : "#252525"}; + color: ${active ? "#4fc3f7" : "#555"}; + font-weight: 700; + font-size: 11px; + cursor: pointer; + letter-spacing: 1px; + box-shadow: ${active ? "0 0 7px rgba(79,195,247,0.25)" : "none"}; + transition: all 0.2s ease; + `; + return btn; + } + const imgBtn = makeChoiceBtn("🖼 IMAGES", true); + const vidBtn = makeChoiceBtn("🎬 VIDÉO", false); + btnRow.appendChild(imgBtn); + btnRow.appendChild(vidBtn); + container.appendChild(btnRow); + // ── État ────────────────────────────────────────────────────────────── + let isVideoMode = false; + const GREY_IN_VIDEO = [ + "temperature", "top_p", "negative_prompt", + "fal_safety_tolerance", "fal_enable_web_search", + "use_search", "system_instructions", "batch_size", + "gpt2_image_quality", + ]; + // ── Grise/dégrise le bloc Automation Face Swap ─────────────────────── + function setFaceSwapGreyed(greyed) { + const fsW = node.widgets?.find(w => w.name === "nb_faceswap_automation"); + const el = fsW?.element; + if (!el) return; + el.style.opacity = greyed ? "0.22" : "1"; + el.style.pointerEvents = greyed ? "none" : "auto"; + el.style.filter = greyed ? "grayscale(80%) brightness(0.35)" : "none"; + app.graph.setDirtyCanvas(true, true); + } + function updateCombo(name, newValues, newDefault) { + const w = getWidget(node, name); + if (!w) return; + if (w.options?.values) w.options.values = [...newValues]; + if (!newValues.includes(w.value)) { + w.value = newDefault; + if (w.callback) w.callback(newDefault); + } + } + // ── Visibilité des widgets vidéo-only ───────────────────────────────── + // Ces widgets sont visibles SI ET SEULEMENT SI on est en mode VIDEO. + function updateVideoOnlyWidgets(visible) { + setWidgetVisible(node, "video_duration", visible); + setWidgetVisible(node, "video_generate_audio", visible); + } + function updateVideoDurationVisibility() { updateVideoOnlyWidgets(node._nbIsVideoMode === true); } + node._nbUpdateVideoDuration = updateVideoDurationVisibility; + // ── Activer le mode IMAGE ───────────────────────────────────────────── + function activateImageMode(initial = false) { + isVideoMode = false; + node._nbIsVideoMode = false; + imgBtn.style.border = "1.5px solid #4fc3f7"; + imgBtn.style.background = "rgba(79,195,247,0.18)"; + imgBtn.style.color = "#4fc3f7"; + imgBtn.style.boxShadow = "0 0 7px rgba(79,195,247,0.25)"; + vidBtn.style.border = "1.5px solid #444"; + vidBtn.style.background = "#252525"; + vidBtn.style.color = "#555"; + vidBtn.style.boxShadow = "none"; + container.style.border = "2px solid #1565c0"; + container.style.background = "linear-gradient(135deg, rgba(21,101,192,0.14) 0%, rgba(79,195,247,0.06) 100%)"; + titleEl.style.color = "#4fc3f7"; + titleEl.style.textShadow = "0 0 10px rgba(79,195,247,0.45)"; + // IMAGE_MODELS_DEFAULT = source de vérité (Python déclare image+vidéo + // pour la validation serveur, donc options.values n'est plus fiable) + const modelW = getWidget(node, "model"); + if (modelW) { + const vals = IMAGE_MODELS_DEFAULT; + if (modelW.options?.values) modelW.options.values = [...vals]; + if (!vals.includes(modelW.value)) { + modelW.value = vals[0]; + if (modelW.callback) modelW.callback(vals[0]); + } + if (modelW._imgOrigTooltip !== undefined) { + if (modelW.options) modelW.options.tooltip = modelW._imgOrigTooltip; + delete modelW._imgOrigTooltip; + } + } + updateCombo("aspect_ratio", IMAGE_ASPECT_RATIOS, "1:1"); + updateCombo("image_size", IMAGE_RESOLUTIONS, "2K"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "image_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, false); + // Re-synchronise batch_size et aspect_ratio (Kling) en mode image + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(false), 60); + if (!initial) { + syncNodeWidget(node, "video_mode_enabled", false); + app.graph.setDirtyCanvas(true, true); + } + } + // ── Activer le mode VIDÉO ───────────────────────────────────────────── + function activateVideoMode() { + isVideoMode = true; + node._nbIsVideoMode = true; + vidBtn.style.border = "1.5px solid #ce93d8"; + vidBtn.style.background = "rgba(206,147,216,0.18)"; + vidBtn.style.color = "#ce93d8"; + vidBtn.style.boxShadow = "0 0 7px rgba(206,147,216,0.3)"; + imgBtn.style.border = "1.5px solid #444"; + imgBtn.style.background = "#252525"; + imgBtn.style.color = "#555"; + imgBtn.style.boxShadow = "none"; + container.style.border = "2px solid #6a1b9a"; + container.style.background = "linear-gradient(135deg, rgba(106,27,154,0.14) 0%, rgba(206,147,216,0.06) 100%)"; + titleEl.style.color = "#ce93d8"; + titleEl.style.textShadow = "0 0 10px rgba(206,147,216,0.45)"; + // VIDEO_MODELS = source de vérité — pas de sauvegarde _imgOrigValues + // car options.values contient maintenant image+vidéo côté Python + const modelW = getWidget(node, "model"); + if (modelW) { + if (modelW.options?.values) modelW.options.values = [...VIDEO_MODELS]; + if (!VIDEO_MODELS.includes(modelW.value)) { + modelW.value = VIDEO_MODELS[0]; + if (modelW.callback) modelW.callback(VIDEO_MODELS[0]); + } + if (modelW.options?.tooltip) { + modelW._imgOrigTooltip = modelW.options.tooltip; + modelW.options.tooltip = ""; + } + } + updateCombo("aspect_ratio", VIDEO_ASPECT_RATIOS, "16:9"); + updateCombo("image_size", VIDEO_RESOLUTIONS, "1080p"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "video_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, true); + // Force batch_size = 1, synchronise aspect_ratio, durée et résolution selon le modèle + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + node._nbSyncKlingDuration?.(); + node._nbSyncVideoResolution?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(true), 60); + syncNodeWidget(node, "video_mode_enabled", true); + app.graph.setDirtyCanvas(true, true); + } + // ── Listeners ───────────────────────────────────────────────────────── + imgBtn.addEventListener("click", () => { if (isVideoMode) activateImageMode(); }); + vidBtn.addEventListener("click", () => { if (!isVideoMode) activateVideoMode(); }); + node._modeToggleAPI = { activateImageMode, activateVideoMode }; + // ── État initial SYNCHRONE (mode image par défaut) ──────────────────── + // Masquer video_duration AVANT d'ajouter le DOM widget évite un + // redimensionnement visible du node ~250 ms après le démarrage. + node._nbIsVideoMode = false; + updateVideoOnlyWidgets(false); + // ── Ajout DOM widget ────────────────────────────────────────────────── + const domWidget = node.addDOMWidget( + "nb_mode_toggle", "mode_toggle_div", container, + { serialize: false, hideOnZoom: false } + ); + if (domWidget) domWidget.computeSize = (w) => [w, 95]; + // ── Placer en PREMIER ───────────────────────────────────────────────── + if (domWidget) { + const idx = node.widgets.indexOf(domWidget); + if (idx > 0) { node.widgets.splice(idx, 1); node.widgets.unshift(domWidget); } + app.graph.setDirtyCanvas(true, true); + } + // ── Filtrage initial du dropdown "model" (mode image par défaut) ───── + // On ne fait QUE filtrer la liste — pas d'appel à activateImageMode() + // pour éviter de déclencher des callbacks qui perturbent la visibilité + // des widgets DOM (inputEl créés après le premier rendu). + setTimeout(() => { + const modelW = getWidget(node, "model"); + if (!modelW || node._nbIsVideoMode) return; + if (modelW.options?.values) modelW.options.values = [...IMAGE_MODELS_DEFAULT]; + if (!IMAGE_MODELS_DEFAULT.includes(modelW.value)) modelW.value = IMAGE_MODELS_DEFAULT[0]; + }, 200); + // ── Sync UI ↔ widget "video_mode_enabled" après chargement workflow ── + // Au chargement d'un workflow, ComfyUI restaure la valeur du widget + // caché `video_mode_enabled`, mais la variable locale isVideoMode reste + // à false. Résultat : l'UI montre IMAGES mais le backend reçoit + // video_mode_enabled=true → "Modèle vidéo inconnu : Nano Banana Pro". + // On fixe ça en synchronisant l'UI avec la valeur réelle du widget ~350ms + // après le onNodeCreated (délai suffisant pour que configure() ait injecté + // les valeurs sauvegardées). + setTimeout(() => { + const videoModeWidget = getWidget(node, "video_mode_enabled"); + const savedIsVideo = videoModeWidget?.value === true; + if (savedIsVideo && !node._nbIsVideoMode) { + // Workflow sauvegardé en mode vidéo → bascule l'UI en vidéo + activateVideoMode(); + } else { + // Force explicitement le widget à false pour éviter qu'une + // valeur "truthy" résiduelle (1, "true"…) passe côté Python + syncNodeWidget(node, "video_mode_enabled", false); + } + }, 350); +} +// ─── Automation Face Swap UI ────────────────────────────────────────────── +function buildFaceSwapUI(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #e65c00; + border-radius: 9px; + padding: 9px 10px 16px 10px; + background: linear-gradient(135deg, + rgba(230,92,0,0.13) 0%, + rgba(255,140,0,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Title ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ AUTOMATION FACE SWAP"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #ff8c00; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(255,140,0,0.45); + margin-bottom: 7px; + transition: color 0.25s, text-shadow 0.25s; + user-select: none; + `; + container.appendChild(titleEl); + // ── Separator ───────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #e65c00 40%, #e65c00 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Info hint ───────────────────────────────────────────────────────── + const hintEl = document.createElement("div"); + hintEl.textContent = "ℹ️ Image 1 = reference face · Image 2 = face to swap"; + hintEl.style.cssText = ` + font-size: 10px; + color: #999; + font-style: italic; + text-align: center; + margin-bottom: 8px; + user-select: none; + `; + container.appendChild(hintEl); + // ── Helper pour construire une ligne "label + bouton ON/OFF" ────────── + function makeToggleRow(labelText, tooltip, hidden = false) { + const row = document.createElement("div"); + row.style.cssText = ` + display: ${hidden ? "none" : "flex"}; + align-items: center; + gap: 8px; + ${hidden ? "margin-top: 8px; padding-top: 7px; border-top: 1px solid rgba(230,92,0,0.3);" : ""} + `; + const label = document.createElement("span"); + label.textContent = labelText; + label.title = tooltip; + label.style.cssText = ` + font-size: 12px; + color: #ccc; + flex: 1; + user-select: none; + `; + const btn = document.createElement("button"); + btn.textContent = "OFF"; + btn.title = tooltip; + btn.style.cssText = TOGGLE_BTN_BASE_CSS; + row.appendChild(label); + row.appendChild(btn); + return { row, btn }; + } + // ── Face Swap toggle ────────────────────────────────────────────────── + const { row: toggleRow, btn: toggleBtn } = makeToggleRow( + "Face Swap", + "Activate to run Automation Face Swap.\nImage 1 = reference face · Image 2 = face to swap", + false + ); + container.appendChild(toggleRow); + // ── Breast Refiner row (hidden until automation ON) ────────────────── + const { row: brRow, btn: brBtn } = makeToggleRow( + "Breast Refiner", + "This tool enhances breast shape by defining the upper curve for a more natural look. May trigger NSFW restrictions.", + true + ); + container.appendChild(brRow); + // ── Low Neck row (hidden until automation ON) ──────────────────────── + const { row: lnRow, btn: lnBtn } = makeToggleRow( + "Low Neck", + "Add a low neck, might be flagged as sensitive content.", + true + ); + container.appendChild(lnRow); + // ── Facial Expression section (hidden until automation ON) ─────────── + const EXPRESSIONS = [ + "Neutral", "Sensual", "Playful", "Subtle smile", "Smile", "Laugh", + ]; + const exprSection = document.createElement("div"); + exprSection.style.cssText = ` + display: none; + flex-direction: column; + gap: 6px; + margin-top: 8px; + padding-top: 7px; + border-top: 1px solid rgba(230,92,0,0.3); + `; + const exprTitleEl = document.createElement("div"); + exprTitleEl.textContent = "Facial Expression"; + exprTitleEl.style.cssText = ` + font-size: 11px; + font-weight: 600; + color: #aaa; + letter-spacing: 0.8px; + user-select: none; + `; + exprSection.appendChild(exprTitleEl); + const exprGrid = document.createElement("div"); + exprGrid.style.cssText = ` + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 4px; + `; + const exprBtns = {}; + function selectExpression(value) { + for (const [v, btn] of Object.entries(exprBtns)) { + const active = (v === value); + btn.style.background = active ? "rgba(255,140,0,0.35)" : "#2a2a2a"; + btn.style.color = active ? "#ff8c00" : "#888"; + btn.style.border = active ? "1.5px solid #e65c00" : "1.5px solid #444"; + btn.style.fontWeight = active ? "700" : "400"; + } + syncNodeWidget(node, "face_expression", value); + } + for (const value of EXPRESSIONS) { + const btn = document.createElement("button"); + btn.textContent = value; + btn.style.cssText = ` + padding: 4px 6px; + border-radius: 10px; + border: 1.5px solid #444; + background: #2a2a2a; + color: #888; + font-size: 10.5px; + cursor: pointer; + transition: all 0.15s ease; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; + btn.addEventListener("click", () => selectExpression(value)); + exprBtns[value] = btn; + exprGrid.appendChild(btn); + } + exprSection.appendChild(exprGrid); + container.appendChild(exprSection); + selectExpression("Neutral"); + // ── State ───────────────────────────────────────────────────────────── + let automationActive = false; + let breastRefinerActive = false; + let lowNeckActive = false; + const FS_HEIGHT_OFF = 115; + const FS_HEIGHT_ON = 300; + let _blockH = FS_HEIGHT_OFF; + // ── Face Swap toggle ────────────────────────────────────────────────── + toggleBtn.addEventListener("click", () => { + automationActive = !automationActive; + _blockH = automationActive ? FS_HEIGHT_ON : FS_HEIGHT_OFF; + setToggleVisual(toggleBtn, automationActive, FS_ON_STYLE); + if (automationActive) { + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + } else { + container.style.border = "2px solid #e65c00"; + container.style.background = "linear-gradient(135deg, rgba(230,92,0,0.13) 0%, rgba(255,140,0,0.06) 100%)"; + titleEl.style.color = "#ff8c00"; + titleEl.style.textShadow = "0 0 10px rgba(255,140,0,0.45)"; + brRow.style.display = "none"; + lnRow.style.display = "none"; + exprSection.style.display = "none"; + // Reset sub-toggles when automation is switched off + if (breastRefinerActive) { + breastRefinerActive = false; + setToggleVisual(brBtn, false, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", false); + } + if (lowNeckActive) { + lowNeckActive = false; + setToggleVisual(lnBtn, false, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", false); + } + } + applyAutomationState(node, automationActive); + syncNodeWidget(node, "face_swap_enabled", automationActive); + // Force la taille immédiatement (pas de latence au premier clic) + const newSize = node.computeSize(); + node.size[0] = Math.max(node.size[0], newSize[0]); + node.size[1] = newSize[1]; + app.graph.setDirtyCanvas(true, true); + }); + // ── Breast Refiner toggle ───────────────────────────────────────────── + brBtn.addEventListener("click", () => { + breastRefinerActive = !breastRefinerActive; + setToggleVisual(brBtn, breastRefinerActive, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", breastRefinerActive); + app.graph.setDirtyCanvas(true); + }); + // ── Low Neck toggle ─────────────────────────────────────────────────── + lnBtn.addEventListener("click", () => { + lowNeckActive = !lowNeckActive; + setToggleVisual(lnBtn, lowNeckActive, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", lowNeckActive); + app.graph.setDirtyCanvas(true); + }); + // ── Add DOM widget to node ──────────────────────────────────────────── + const domWidget = node.addDOMWidget("nb_faceswap_automation", "automation_div", container, { + serialize: false, + hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + // ── Restaure l'état sauvegardé dans le workflow ─────────────────────── + // Le DOM démarre à OFF par défaut ; on le réaligne sur les widgets Python + // pour que l'état visuel corresponde toujours à ce qui sera exécuté. + const _savedFS = getWidget(node, "face_swap_enabled")?.value === true; + if (_savedFS) { + automationActive = true; + _blockH = FS_HEIGHT_ON; + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + setToggleVisual(toggleBtn, true, FS_ON_STYLE); + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + applyAutomationState(node, true); + } + // Breast Refiner et Low Neck : toujours OFF au démarrage. + // On réinitialise le widget Python même si le workflow les avait sauvegardés + // à true, pour éviter qu'ils se réactivent silencieusement entre sessions. + syncNodeWidget(node, "breast_refiner_enabled", false); + syncNodeWidget(node, "low_neck_enabled", false); + // breastRefinerActive et lowNeckActive restent false, boutons restent OFF. + // Masque les widgets Python cachés (IMMÉDIATEMENT, pas en setTimeout, pour + // éviter que le node soit dessiné grand puis rétréci juste après). + const HIDDEN_PY_WIDGETS = [ + "face_swap_enabled", "breast_refiner_enabled", "low_neck_enabled", + "face_expression", "video_mode_enabled", + ]; + for (const name of HIDDEN_PY_WIDGETS) { + const w = getWidget(node, name); + if (!w) continue; + w._fsOrigComputeSize = w.computeSize; + w.computeSize = () => [0, -4]; + w.hidden = true; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + } + app.graph.setDirtyCanvas(true, true); +} +// ─── Preset panel (10 slots, mode-aware, avec champ nom) ────────────────── +function buildPresetUI(node) { + const NUM_PRESETS = 10; + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #37474f; + border-radius: 9px; + padding: 8px 10px 10px 10px; + background: linear-gradient(135deg, + rgba(55,71,79,0.14) 0%, + rgba(96,125,139,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + `; + forwardWheelToCanvas(container); + const titleEl = document.createElement("div"); + titleEl.textContent = "💾 PRESETS"; + titleEl.style.cssText = ` + font-weight: 700; font-size: 11.5px; color: #90a4ae; + letter-spacing: 2px; text-align: center; + margin-bottom: 7px; user-select: none; + `; + container.appendChild(titleEl); + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #37474f 40%, #37474f 60%, transparent); + opacity: 0.55; margin-bottom: 7px; + `; + container.appendChild(sep); + const list = document.createElement("div"); + list.style.cssText = "display: flex; flex-direction: column; gap: 4px;"; + container.appendChild(list); + const slotRows = {}; + const slotInputs = {}; + function markSlotFilled(n, filled, name) { + const row = slotRows[n]; + const input = slotInputs[n]; + if (!row) return; + row.style.border = filled ? "1px solid rgba(79,195,247,0.3)" : "1px solid #2a2a2a"; + row.style.background = filled ? "rgba(79,195,247,0.04)" : "#1a1a1a"; + if (input && name !== undefined) input.value = name || ""; + } + function buildSlot(n) { + const row = document.createElement("div"); + row.style.cssText = ` + display: flex; align-items: center; gap: 4px; + padding: 3px 5px; border-radius: 6px; + border: 1px solid #2a2a2a; background: #1a1a1a; + transition: border 0.2s, background 0.2s; + `; + slotRows[n] = row; + const label = document.createElement("span"); + label.textContent = `${n < 10 ? " " : ""}${n}`; + label.style.cssText = ` + font-size: 9.5px; color: #555; min-width: 14px; + user-select: none; font-weight: 700; font-variant-numeric: tabular-nums; + `; + const nameInput = document.createElement("input"); + nameInput.type = "text"; + nameInput.placeholder = `preset ${n}`; + nameInput.style.cssText = ` + flex: 1; min-width: 0; + background: #111; border: 1px solid #333; border-radius: 4px; + color: #aaa; font-size: 9.5px; padding: 2px 5px; + outline: none; font-family: 'Segoe UI', Arial, sans-serif; + `; + nameInput.addEventListener("focus", () => nameInput.style.borderColor = "#546e7a"); + nameInput.addEventListener("blur", () => nameInput.style.borderColor = "#333"); + nameInput.addEventListener("keydown", e => e.stopPropagation()); + slotInputs[n] = nameInput; + const btnBase = ` + padding: 2px 8px; border-radius: 4px; font-size: 9px; + font-weight: 700; cursor: pointer; white-space: nowrap; + transition: all 0.15s ease; letter-spacing: 0.4px; + `; + const saveBtn = document.createElement("button"); + saveBtn.textContent = "SAVE"; + saveBtn.title = `Sauvegarder dans le slot ${n}`; + saveBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + const loadBtn = document.createElement("button"); + loadBtn.textContent = "LOAD"; + loadBtn.title = `Charger le slot ${n}`; + loadBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + row.appendChild(label); + row.appendChild(nameInput); + row.appendChild(saveBtn); + row.appendChild(loadBtn); + list.appendChild(row); + saveBtn.addEventListener("click", async () => { + const params = { preset_name: nameInput.value.trim() }; + for (const w of node.widgets || []) { + if (w.name && w.value !== undefined + && w.type !== "button" && w.type !== "dom_widget" + && !w.name.startsWith("nb_")) { + params[w.name] = w.value; + } + } + try { + const res = await fetch("/nb_aio/save_preset", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ slot: n, params }), + }); + const data = await res.json(); + if (data.success) { + markSlotFilled(n, true, params.preset_name); + saveBtn.style.cssText = btnBase + "border:1px solid #00c853; background:#1b5e20; color:#69f0ae;"; + setTimeout(() => { + saveBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + } + } catch (e) { console.error("[NB Presets] Save error:", e); } + }); + loadBtn.addEventListener("click", async () => { + try { + const res = await fetch("/nb_aio/load_presets"); + const data = await res.json(); + if (!data.success) return; + const preset = data.presets?.[String(n)]; + if (!preset) return; + const isVideo = preset.video_mode_enabled === true; + if (isVideo && !node._nbIsVideoMode) { + node._modeToggleAPI?.activateVideoMode(); + } else if (!isVideo && node._nbIsVideoMode) { + node._modeToggleAPI?.activateImageMode(); + } + if (preset.preset_name !== undefined) { + nameInput.value = preset.preset_name || ""; + } + markSlotFilled(n, true, preset.preset_name); + const SKIP = new Set(["video_mode_enabled", "preset_name"]); + for (const [key, value] of Object.entries(preset)) { + if (SKIP.has(key)) continue; + syncNodeWidget(node, key, value); + } + loadBtn.style.cssText = btnBase + "border:1px solid #2962ff; background:#0d47a1; color:#82b1ff;"; + setTimeout(() => { + loadBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + app.graph.setDirtyCanvas(true, true); + } catch (e) { console.error("[NB Presets] Load error:", e); } + }); + } + for (let i = 1; i <= NUM_PRESETS; i++) buildSlot(i); + const PANEL_H = 368; + const domWidget = node.addDOMWidget("nb_presets_ui", "presets_div", container, { + serialize: false, hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, PANEL_H]; + fetch("/nb_aio/load_presets") + .then(r => r.json()) + .then(data => { + if (!data.success) return; + for (let i = 1; i <= NUM_PRESETS; i++) { + const p = data.presets?.[String(i)]; + if (p) markSlotFilled(i, true, p.preset_name); + } + }) + .catch(() => {}); +} +// ─── Prompt widget colour coding ────────────────────────────────────────── +function stylePromptWidgets(node) { + setTimeout(() => { + const pos = getWidget(node, "prompt"); + if (pos?.inputEl) { + pos.inputEl.style.borderLeft = "3px solid #00c853"; + pos.inputEl.style.paddingLeft = "6px"; + pos.inputEl.style.borderRadius = "3px"; + } + const neg = getWidget(node, "negative_prompt"); + if (neg?.inputEl) { + neg.inputEl.style.borderLeft = "3px solid #e53935"; + neg.inputEl.style.paddingLeft = "6px"; + neg.inputEl.style.borderRadius = "3px"; + } + }, 200); +} +// ─── Extension registration ─────────────────────────────────────────────── +app.registerExtension({ + name: "NanoBananaAIO.FaceSwap", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "NanoBananaAIO") return; + const onCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onCreated?.apply(this, arguments); + const node = this; + stylePromptWidgets(node); + // Mode toggle en premier (synchrone) — place le widget tout en haut + buildModeToggle(node); + setTimeout(() => setupKlingAspectRatioSync(node), 500); + setTimeout(() => setupKlingDurationSync(node), 500); + setTimeout(() => setupProviderBatchSync(node), 500); + setTimeout(() => setupGPT2Sync(node), 500); + setTimeout(() => setupVideoResolutionSync(node), 500); + setTimeout(() => buildFaceSwapUI(node), 400); + setTimeout(() => buildPresetUI(node), 450); + // Nettoyage tardif des widgets preset hérités (autre JS) + setTimeout(() => { + if (!node.widgets) return; + const KEEP = new Set([ + "nb_faceswap_automation", "nb_presets_ui", "nb_mode_toggle", + "face_expression", "face_swap_enabled", "breast_refiner_enabled", + "low_neck_enabled", "video_mode_enabled", + ]); + const isLegacy = (w) => { + if (!w.name) return false; + if (KEEP.has(w.name)) return false; + if (w.name.startsWith("nb_")) return false; + const n = w.name.toLowerCase(); + return ( + w.type === "button" || + n.includes("preset") || + n.includes("slot") + ); + }; + for (let i = node.widgets.length - 1; i >= 0; i--) { + const w = node.widgets[i]; + if (!isLegacy(w)) continue; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + node.widgets.splice(i, 1); + } + // Force-hide des widgets Python automation (canvas widgets LiteGraph) + for (const name of ["face_expression", "face_swap_enabled", + "breast_refiner_enabled", "low_neck_enabled", + "video_mode_enabled"]) { + const w = getWidget(node, name); + if (!w) continue; + w.hidden = true; + w.computeSize = () => [0, -4]; + if (w.inputEl) { try { w.inputEl.remove(); } catch (_) {} w.inputEl = null; } + if (w.element) { try { w.element.remove(); } catch (_) {} w.element = null; } + } + app.graph.setDirtyCanvas(true, true); + }, 1200); + }; + }, +}); \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260426_025322_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260426_025322_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..f26b3b36d6a4045df6959a06cb96b4a5367556cb --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260426_025322_nano_banana_aio.py @@ -0,0 +1,6409 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260426_123725_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260426_123725_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..15f4a8ce03a57bc5a5e4d5d1426ccf6e941b1635 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260426_123725_nano_banana_aio.py @@ -0,0 +1,6421 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260426_133135_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260426_133135_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..1880cbe34c456d5a145ce22823ae7dc1b328dc36 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260426_133135_nano_banana_aio.py @@ -0,0 +1,6436 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Réponse pretty-printed parsée depuis le buffer complet.") + except Exception as _pe: + print(f"⚠️ {tag} Buffer complet non parseable : {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260426_145320_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260426_145320_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..8d41cfe21b4c4d023d9fd4aa37aa288553468845 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260426_145320_nano_banana_aio.py @@ -0,0 +1,6441 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI.", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Réponse pretty-printed parsée depuis le buffer complet.") + except Exception as _pe: + print(f"⚠️ {tag} Buffer complet non parseable : {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260426_151010_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260426_151010_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..20ccf92aa1517648d46b446f84382ed1af7a150a --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260426_151010_nano_banana_aio.py @@ -0,0 +1,6446 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Réponse pretty-printed parsée depuis le buffer complet.") + except Exception as _pe: + print(f"⚠️ {tag} Buffer complet non parseable : {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260426_151836_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260426_151836_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..4bfa72b00caa648722e2a39517503edf78f92138 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260426_151836_nano_banana_aio.py @@ -0,0 +1,6446 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + except Exception: + buffer += raw_chunk + "\n" # remettre le newline strippé par iter_lines + try: + chunk = _json.loads(buffer.strip().rstrip(",")) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Réponse pretty-printed parsée depuis le buffer complet.") + except Exception as _pe: + print(f"⚠️ {tag} Buffer complet non parseable : {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260427_163353_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260427_163353_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc49ecf0aac2184b52a2dccd98eb156559dfc3d --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260427_163353_nano_banana_aio.py @@ -0,0 +1,6448 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne réussi, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Réponse pretty-printed parsée depuis le buffer complet.") + except Exception as _pe: + print(f"⚠️ {tag} Buffer complet non parseable : {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260427_170113_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260427_170113_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..50da364a8cd3e876ff450b46fb7aa1b81a3d3cc0 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260427_170113_nano_banana_aio.py @@ -0,0 +1,6463 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignoré automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le modèle ET la résolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En attente de la réponse"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s écoulées)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur non supportée est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Impossible de charger : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Sauvegardé → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Erreur sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} sauvegardé via bouton JS") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanoBanana] Routes /nb_aio déjà enregistrées — second chargement ignoré.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] Échec installation fal-client : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installé avec succès !") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Échec installation google-auth : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Impossible d'installer google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Le chemin vers le fichier JSON Vertex AI est vide.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Fichier JSON Vertex AI introuvable : {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Fichier JSON invalide : {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs manquants : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Type de credentials non supporté : '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials chargés — projet : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Le chemin du dossier Vertex AI JSON est vide.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Dossier Vertex AI JSON introuvable : {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ Aucun fichier .json trouvé dans : {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | modèle={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les résolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du modèle", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres modèles.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Le prompt ne peut pas être vide.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le modèle + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignoré.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignoré.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder manquant pour le provider VERTEX." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} projet(s) détecté(s)") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projets={len(vj_files)} → batch réduit à {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key manquante pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size doit être entre 1 et 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Échoué — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} réussies\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex AI ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Modèle : {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de créer le client Vertex AI : {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} ajoutée au contexte...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Génération en cours (modèle={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur API Vertex AI : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} Aucun candidat retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Génération bloquée : finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json manquant (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Vertex NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth non disponible.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} Token OAuth2 obtenu (projet={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible d'obtenir le token OAuth2 : {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Envoi requête NB2 streaming (timeout : {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En attente de la réponse") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne réussi, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} détecté dans le stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} Premier chunk reçu, génération en cours...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Réponse pretty-printed parsée depuis le buffer complet.") + except Exception as _pe: + print(f"⚠️ {tag} Buffer complet non parseable : {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} Erreur API : code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} Pas d'image générée (finishReason={finish}{detail})\n" + f" Texte reçu : {text_in}", _batch_idx + ) + else: + # Aucun candidat — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "réponse vide (0 candidats, pas de promptFeedback)" + print(f"🔍 {tag} Premiers octets reçus : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Requête bloquée ou réponse vide — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Taille non mappée → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Soumission GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} Erreur API : {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Erreurs HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Erreur HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Arrêt : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Soumission Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 Kie ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le modèle selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Upload des images échoué (ws_api_key nécessaire pour img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible avec 1:1 et aspect_ratio auto → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2 : 4K incompatible avec aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Soumission GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Soumission → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Échoué — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont échoué :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) non mappé → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key manquante !", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur upload image {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Soumission → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL manquante.", _batch_idx) + + print(f"✅ {tag} Image prête ! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur : {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Échoué — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Ajout image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Envoi requête NB2 (timeout : {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Réponse JSON invalide : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Génération réussie !") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout après {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur réseau : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key manquante !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Utilisation d'un modèle preview : {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool non supporté : {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — génération en cours...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"L'API Google n'a retourné aucun candidat (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Génération Google échouée : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("Aucune donnée image dans la réponse Google.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — génération réussie !") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Démarrage...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"Aucun candidat — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Réussi !") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Génération parallèle de {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Échoué — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Terminé ! {len(generated_images)}/{batch_size} réussies\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"Toutes les générations ont échoué : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key manquante !", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed nécessite au moins une image source.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Upload de {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Upload image {idx} échoué : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploadée") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur upload image {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission ({model_label}, résolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Erreur soumission : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN échoué ({e}), essai catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe échoué : {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key manquante !", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Génération parallèle de {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Échoué — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont échoué : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("Aucune image valide.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) échouée(s)\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Conversion de {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Soumission {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission échouée : {data.get('msg', 'erreur inconnue')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll erreur : {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing erreur : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Terminé !\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Téléchargement échoué : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Modèle non compatible → forcé : Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masquage du visage dans l'image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Envoi vers {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} projet(s) détecté(s)") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projets={len(_vj_files)} → batch réduit à {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projets utilisés : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key manquante pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} ajoutée au contexte Google...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de résolution ──────────────────────────────────── + # Seedance : 4K non supporté (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres modèles snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres modèles vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la résolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key manquante pour Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key manquante pour Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key manquante pour Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider non supporté ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key manquante pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder manquant pour le provider VERTEX." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key manquante pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key manquante pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key manquante pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le modèle '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les modèles Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Impossible de créer le client Google : {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s hors plage API (4-8s), ajustée à {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Mode image-to-video (image_1 utilisée comme référence)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Génération en cours (peut prendre plusieurs minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente...") + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} Aucune vidéo retournée par l'API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — modèle={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket reçu : {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Impossible d'encoder l'image : {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri envoyé : {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Opération lancée : {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lancement : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Génération en cours...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Erreur polling ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Vidéo décodée depuis base64 ({len(video_bytes)} octets).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} Vidéo GCS : {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Lecture réponse : {e}") + + # ── 7. Téléchargement depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée depuis GCS ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — mode text-to-video.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Fichier vidéo introuvable : {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Erreur upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_out_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué, mode text-to-video.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} durée {duration}s ajustée à {duration_clamped}s (plage 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | résolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignoré — Kie.ai inclut toujours l'audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Soumission refusée : {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId dans la réponse : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération échouée : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] en attente (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement vidéo : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image échoué — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 6. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initialisation — durée={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (résolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignorées. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image {idx+1} échoué, ignoré.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Soumission échouée : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Complété mais aucun output vidéo.") + video_url = outputs[0] + print(f"✅ {tag} Vidéo prête ! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Erreur inconnue") + return self._handle_error(f"❌ {tag} Génération échouée : {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image début échoué : {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image fin échoué : {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Soumission...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | résolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image début échoué.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Upload image fin échoué, ignoré.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Soumission...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} Pas de taskId : {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling erreur ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll erreur : {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Tâche terminée ! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing réponse : {e}") + + # ── 5. Téléchargement ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Résolution {resolution!r} non disponible sur FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon résolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} non supporté → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Téléchargement ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference manquant.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — sera ignorée.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} Upload FAL échoué ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur lecture vidéo référence : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Génération en cours...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Erreur : {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Téléchargement ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} Aucune URL vidéo dans la réponse : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Impossible d'installer fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | résolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Upload image échoué : {e} — mode text-to-video.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Attente résultat (timeout : {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Terminé ! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Erreur status ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout après {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur soumission : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} Aucune URL vidéo dans la réponse.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes)} octets).") + except Exception as e: + return self._handle_error(f"❌ {tag} Erreur téléchargement : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Impossible de sauvegarder la vidéo : {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Terminé ! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} Aucune métadonnée à supprimer.") + except Exception as e: + print(f"⚠️ {tag} Erreur strip métadonnées : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} Pas de fichier vidéo — retour d'un tensor vide.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 non disponible — impossible d'extraire les frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Erreur extraction frames : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260427_195019_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260427_195019_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..29c021703491df942877ed0a0a4812c290410691 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260427_195019_nano_banana_aio.py @@ -0,0 +1,6463 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur KIE.\n" + "→ Utilisez FAL pour la resolution 4K, ou sélectionnez 720p / 1080p." + ) + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if model == "Kling 3.0" and video_resolution == "4K": + return self._handle_error( + "❌ [Video] Kling 3.0 4K n'est pas encore disponible sur WaveSpeed.\n" + "→ Utilisez FAL pour la resolution 4K, ou sélectionnez 720p / 1080p." + ) + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "Pro" if resolution == "1080p" else "Standard" + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # pro = 1080p (resolution max) | std = 720p + mode_api = "pro" if resolution == "1080p" else "std" + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260428_165727_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260428_165727_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..4e15508624c1b0db11b41bf856ad296ec96384e0 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260428_165727_nano_banana_aio.py @@ -0,0 +1,6454 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + try: + with _Heartbeat(f"{tag} En cours"): + response = client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260429_210340_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260429_210340_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9c7f7bf864b94d62a33c84b10734aa9e910c18 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260429_210340_nano_banana_aio.py @@ -0,0 +1,6500 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + try: + http_opts = genai.types.HttpOptions(timeout=320, max_retries=0) + except Exception: + http_opts = None + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=380) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + # Executor managed manually (no "with") so shutdown(wait=False) can be + # called on timeout — avoids blocking until the SDK thread actually exits. + _tex = ThreadPoolExecutor(max_workers=1) + try: + with _Heartbeat(f"{tag} En cours"): + _VERTEX_CALL_TIMEOUT = 350 # hard cutoff indépendant du SDK + _fut = _tex.submit( + client.models.generate_content, + model=vertex_model_id, contents=contents, config=config + ) + try: + response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError: + _tex.shutdown(wait=False) # release immediately, don't block + return self._handle_error( + f"❌ {tag} Timeout after {_VERTEX_CALL_TIMEOUT}s (no response from Vertex AI).", + _batch_idx + ) + except Exception as e: + _tex.shutdown(wait=False) + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + _tex.shutdown(wait=False) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260429_210927_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260429_210927_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..9972c1890dcebdce986e05599c5b0051a7978979 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260429_210927_nano_banana_aio.py @@ -0,0 +1,6513 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = (location or "us-central1").strip() or "us-central1" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (180_000, 180): + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Diagnostic — confirme la valeur effective de temperature/top_p envoyée à l'API. + print(f"🌡️ {tag} temperature={temperature} | top_p={top_p}") + try: + _payload_preview = config.model_dump(exclude_none=True) if hasattr(config, "model_dump") else None + if _payload_preview: + print(f"🔍 {tag} generationConfig sent: {_payload_preview}") + except Exception as _e_dump: + print(f" {tag} (config dump unavailable: {_e_dump})") + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + # Executor managed manually (no "with") so shutdown(wait=False) can be + # called on timeout — avoids blocking until the SDK thread actually exits. + _tex = ThreadPoolExecutor(max_workers=1) + try: + with _Heartbeat(f"{tag} En cours"): + _VERTEX_CALL_TIMEOUT = 250 # hard cutoff indépendant du SDK (était 350) + _fut = _tex.submit( + client.models.generate_content, + model=vertex_model_id, contents=contents, config=config + ) + try: + response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError: + _tex.shutdown(wait=False) # release immediately, don't block + return self._handle_error( + f"❌ {tag} Timeout after {_VERTEX_CALL_TIMEOUT}s (no response from Vertex AI).", + _batch_idx + ) + except Exception as e: + _tex.shutdown(wait=False) + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + _tex.shutdown(wait=False) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260429_211040_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260429_211040_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..633f82e34949c9f40f82da413e723eb99ce45f36 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260429_211040_nano_banana_aio.py @@ -0,0 +1,6513 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = (location or "us-central1").strip() or "us-central1" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (180_000, 180): + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 2.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Diagnostic — confirme la valeur effective de temperature/top_p envoyée à l'API. + print(f"🌡️ {tag} temperature={temperature} | top_p={top_p}") + try: + _payload_preview = config.model_dump(exclude_none=True) if hasattr(config, "model_dump") else None + if _payload_preview: + print(f"🔍 {tag} generationConfig sent: {_payload_preview}") + except Exception as _e_dump: + print(f" {tag} (config dump unavailable: {_e_dump})") + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + # Executor managed manually (no "with") so shutdown(wait=False) can be + # called on timeout — avoids blocking until the SDK thread actually exits. + _tex = ThreadPoolExecutor(max_workers=1) + try: + with _Heartbeat(f"{tag} En cours"): + _VERTEX_CALL_TIMEOUT = 250 # hard cutoff indépendant du SDK (était 350) + _fut = _tex.submit( + client.models.generate_content, + model=vertex_model_id, contents=contents, config=config + ) + try: + response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError: + _tex.shutdown(wait=False) # release immediately, don't block + return self._handle_error( + f"❌ {tag} Timeout after {_VERTEX_CALL_TIMEOUT}s (no response from Vertex AI).", + _batch_idx + ) + except Exception as e: + _tex.shutdown(wait=False) + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + _tex.shutdown(wait=False) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260429_211915_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260429_211915_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..9972c1890dcebdce986e05599c5b0051a7978979 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260429_211915_nano_banana_aio.py @@ -0,0 +1,6513 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = (location or "us-central1").strip() or "us-central1" + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (180_000, 180): + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Diagnostic — confirme la valeur effective de temperature/top_p envoyée à l'API. + print(f"🌡️ {tag} temperature={temperature} | top_p={top_p}") + try: + _payload_preview = config.model_dump(exclude_none=True) if hasattr(config, "model_dump") else None + if _payload_preview: + print(f"🔍 {tag} generationConfig sent: {_payload_preview}") + except Exception as _e_dump: + print(f" {tag} (config dump unavailable: {_e_dump})") + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + # Executor managed manually (no "with") so shutdown(wait=False) can be + # called on timeout — avoids blocking until the SDK thread actually exits. + _tex = ThreadPoolExecutor(max_workers=1) + try: + with _Heartbeat(f"{tag} En cours"): + _VERTEX_CALL_TIMEOUT = 250 # hard cutoff indépendant du SDK (était 350) + _fut = _tex.submit( + client.models.generate_content, + model=vertex_model_id, contents=contents, config=config + ) + try: + response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError: + _tex.shutdown(wait=False) # release immediately, don't block + return self._handle_error( + f"❌ {tag} Timeout after {_VERTEX_CALL_TIMEOUT}s (no response from Vertex AI).", + _batch_idx + ) + except Exception as e: + _tex.shutdown(wait=False) + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + _tex.shutdown(wait=False) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpGVUxMIFNDRU5FIFJFRFJBVyDigJQgQ1JJVElDQUwgSU5TVFJVQ1RJT046CuKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgeKUgQpQaWN0dXJlIDIgZGVmaW5lcyB0aGUgRU5USVJFIHNjZW5lOiBwb3NlLCBib2R5LCBjbG90aGluZywgYmFja2dyb3VuZCwgCmxpZ2h0aW5nLCBlbnZpcm9ubWVudCBhbmQgY29tcG9zaXRpb24uIFJlcHJvZHVjZSBBTEwgb2YgaXQgZmFpdGhmdWxseS4KSG93ZXZlciwgZG8gTk9UIHNpbXBseSB1cHNjYWxlIG9yIHBhdGNoIHBpY3R1cmUgMi4KSW5zdGVhZCwgdXNlIHBpY3R1cmUgMiBhcyBhIGZ1bGwgc2NlbmUgYmx1ZXByaW50IGFuZCBSRURSQVcgCnRoZSBlbnRpcmUgaW1hZ2UgZnJvbSBzY3JhdGNoIGF0IG1heGltdW0gcmVzb2x1dGlvbiBhbmQgc2hhcnBuZXNzIOKAlAphcyBpZiBhIHBob3RvZ3JhcGhlciByZXRvb2sgdGhpcyBleGFjdCBzYW1lIHNob3QgaW4gcGVyZmVjdCBjb25kaXRpb25zLgpFdmVyeSBlbGVtZW50IG11c3QgYmUgZnJlc2hseSBnZW5lcmF0ZWQ6IGJvZHksIGNsb3RoaW5nLCBiYWNrZ3JvdW5kLCAKZW52aXJvbm1lbnQsIGxpZ2h0aW5nIOKAlCBhbGwgcmVidWlsdCBmcm9tIHNjcmF0Y2ggYmFzZWQgb24gcGljdHVyZSAyLgpUaGUgc2NlbmUsIHRoZSBzZXR0aW5nIGFuZCB0aGUgYXRtb3NwaGVyZSBtdXN0IGJlIAppZGVudGljYWwgdG8gcGljdHVyZSAyLCBidXQgcmVuZGVyZWQgYXMgYSBicmFuZCBuZXcgc2hhcnAgUkFXIHBob3RvCgoKCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBoYXplLCBubyBzb2Z0IGdsb3csIG5vIHNtb290aGluZywgbm8gbW90aW9uIGJsdXIuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMuIHN1YnRsZXMgZGVybWFsIGltcGVyZmVjdGlvbnMgb24gdGhlIHNraW4sIHBhcyBkZSB0YWNoZXMgc3VyIGxhIHBlYXUsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260430_003129_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260430_003129_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..baff52364b50948750400ad0d14e6c7f2547a9bd --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260430_003129_nano_banana_aio.py @@ -0,0 +1,6505 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (180_000, 180): + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + # Executor managed manually (no "with") so shutdown(wait=False) can be + # called on timeout — avoids blocking until the SDK thread actually exits. + _tex = ThreadPoolExecutor(max_workers=1) + try: + with _Heartbeat(f"{tag} En cours"): + _VERTEX_CALL_TIMEOUT = 250 # hard cutoff indépendant du SDK (était 350) + _fut = _tex.submit( + client.models.generate_content, + model=vertex_model_id, contents=contents, config=config + ) + try: + response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError: + _tex.shutdown(wait=False) # release immediately, don't block + return self._handle_error( + f"❌ {tag} Timeout after {_VERTEX_CALL_TIMEOUT}s (no response from Vertex AI).", + _batch_idx + ) + except Exception as e: + _tex.shutdown(wait=False) + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + _tex.shutdown(wait=False) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except TimeoutError: + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout global après {NB2_TIMEOUT_S + 30}s" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [NB2 Batch {tid}] {msg}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKCmluc3RhZ3JhbSB2aWJlcwpleGFjdCBzYW1lIGNsb3RoZXMgZm9ybSB0aGUgcGljdHVyZSAyLCBzYW1lIGJvZHkgZm9ybSB0aGUgcGljdHVyZSAyLCBFeGFjdCBzYW1lIHBvc2UgZnJvbSB0aGUgcGljdHVyZSAyLgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDIKCgpQSE9UT1JFQUxJU1RJQwoKCkNhbWVyYS9sb29rOgpBbWF0ZXVyIHNtYXJ0cGhvbmUgcmF3IGNyaXNwbmVzcywgbm8gcG9ydHJhaXQgbW9kZS4gZXZlcnl0aGluZyBpcyBzaGFycCwgaW1tZW5zZSBkZXRhaWwuCkRlZXAgZm9jdXMsIGVudGlyZSBzY2VuZSBpbiBmb2N1cy4KTm8gaGF6ZSwgbm8gZ2xvdywgbm8gc21vb3RoaW5nLgpDcmlzcCBhbmQgZGV0YWlsZWQgc2tpbiB0ZXh0dXJlIHdpdGggdmlzaWJsZSBwb3JlcywgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uCk5vIGJva2VoLCBubyBzaGFsbG93IGRlcHRoIG9mIGZpZWxkLCBubyBtb3Rpb24gYmx1ci4gOEsgbmF0aXZlIHJlc29sdXRpb24sIFVMVFJBIERFVEFJTEVELCBmZXcgc3VidGxlcyBza2luIGltcGVyZmVjdGlvbnMsIHBhcyBkZSBib3V0b25zLCBwb3JlcyB2aXNpYmxlcywgbWFzdGVycGllY2UsIGNyaXNweSBza2luLg==" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260430_030157_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260430_030157_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..493c93c93cb39b12cf7f23ef1e88e6e0bc78121e --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260430_030157_nano_banana_aio.py @@ -0,0 +1,6543 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (180_000, 180): + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + # Executor managed manually (no "with") so shutdown(wait=False) can be + # called on timeout — avoids blocking until the SDK thread actually exits. + _tex = ThreadPoolExecutor(max_workers=1) + try: + with _Heartbeat(f"{tag} En cours"): + _VERTEX_CALL_TIMEOUT = 250 # hard cutoff indépendant du SDK (était 350) + _fut = _tex.submit( + client.models.generate_content, + model=vertex_model_id, contents=contents, config=config + ) + try: + response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError: + _tex.shutdown(wait=False) # release immediately, don't block + return self._handle_error( + f"❌ {tag} Timeout after {_VERTEX_CALL_TIMEOUT}s (no response from Vertex AI).", + _batch_idx + ) + except Exception as e: + _tex.shutdown(wait=False) + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + _tex.shutdown(wait=False) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _processed2 = set() + _NB2_OUTER = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUTER): + _processed2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FuturesTE2: + print("⚠️ [Vertex NB2] as_completed timeout — salvage des futures terminés...") + for _f, _i in futures.items(): + if _f in _processed2: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fidx}] Récupéré depuis future terminé") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex NB2 Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex NB2 Batch {_fidx}] Outer timeout — still running") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _processed = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FuturesTE: + print("⚠️ [Google NB2] as_completed timeout — salvage des futures terminés...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fidx}] Récupéré depuis future terminé") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [NB2 Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [NB2 Batch {_fidx}] Outer timeout — still running") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKClNpbWlsYXIgaGFpcnN0eWxlIGZyb20gdGhlIHBpY3R1cmUgMSwgc2FtZSBjbG90aGVzIGZyb20gdGhlIHBpY3R1cmUgMi4KCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBzbW9vdGhpbmcuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260430_030747_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260430_030747_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..493c93c93cb39b12cf7f23ef1e88e6e0bc78121e --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260430_030747_nano_banana_aio.py @@ -0,0 +1,6543 @@ +""" +NanoBananaAIO — Node unifié multimodal. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +Clés API : connectez un node ApiKeysLoaderNode aux entrées correspondantes. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"ignored automatiquement — renommez-le en .py.bak pour éviter ce message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 500 # ~8 min 20s max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Parcourt récursivement les boxes MP4 et : + - vide le contenu de l'atom 'udta' (contient Encoder, copyright, etc.) + - met à zéro le champ manufacturer dans les boxes 'hdlr' (HandlerVendorID) + Retourne True si des modifications ont été effectuées. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Retourne un chemin dans le dossier temp de ComfyUI (ou /tmp si non dispo). + Le fichier est nommé VID_AAAAMMJJ_HHMMSS pour qu'il soit bien nommé au téléchargement.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Thread daemon qui log périodiquement l'attente en cours. + + Utilisé pour les requêtes HTTP synchrones (Google NB2, Vertex NB2 + streaming) afin que l'utilisateur voie que la génération est en + cours et ne pense pas que ComfyUI est gelé. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Slot invalide (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "Échec écriture fichier"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError inclut le payload complet (prompt, images…) — on extrait + juste le champ 'msg' si présent, sinon on tronque à max_len caractères.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[tronqué]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploadée → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Fichier JSON incomplet — champs missings : {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scanne un dossier et retourne la liste triée des fichiers .json (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connexion — projet={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (180_000, 180): + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Prompt de génération / transformation", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — éléments à éviter dans l'image.\n⚠️ Supporté par : FAL, WaveSpeed (NB2), KIE.\nIgnoré par Google / Vertex (Gemini ne supporte pas les negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Résolution de la sortie (image: 1K/2K/4K · vidéo: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Clé API Google AI Studio.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] Clé API WaveSpeed.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Clé API Kie.ai.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Clé API Fal.ai.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Chemin vers le dossier contenant les fichiers JSON des service accounts (1 fichier .json = 1 projet = 1 slot batch).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Désactiver le filtre de sécurité.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Modèle à utiliser.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Nombre d'images à générer en parallèle", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Activer Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] Instructions système", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Générer la piste audio. Supporté par tous les providers Veo.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Créativité du model", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissif", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Activer la recherche web", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Qualité de génération. Ignoré sur les autres models.", + }), + "image_1": ("IMAGE", {"tooltip": "Image source principale"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connectez un nœud 'Aiorbust Video Loader'.\n" + "La durée de la vidéo générée sera égale à celle de la référence.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Activé par le toggle JS — ne pas modifier manuellement.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Activé par le bloc JS — ne pas modifier manuellement.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Expression faciale — géré par le bloc JS — ne pas modifier manuellement.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 est uniquement disponible via WAVESPEED, KIE ou FAL.\n" + "→ Sélectionnez l'un de ces trois providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 n'est pas disponible avec le provider {provider}.\n" + "Sélectionnez WAVESPEED, KIE ou FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 nécessite au moins une image d'entrée." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing pour Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Ratio invalide : {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"image_size invalide : {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + print(f"🚀 {tag} Generating (model={vertex_model_id})...") + # Executor managed manually (no "with") so shutdown(wait=False) can be + # called on timeout — avoids blocking until the SDK thread actually exits. + _tex = ThreadPoolExecutor(max_workers=1) + try: + with _Heartbeat(f"{tag} En cours"): + _VERTEX_CALL_TIMEOUT = 250 # hard cutoff indépendant du SDK (était 350) + _fut = _tex.submit( + client.models.generate_content, + model=vertex_model_id, contents=contents, config=config + ) + try: + response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError: + _tex.shutdown(wait=False) # release immediately, don't block + return self._handle_error( + f"❌ {tag} Timeout after {_VERTEX_CALL_TIMEOUT}s (no response from Vertex AI).", + _batch_idx + ) + except Exception as e: + _tex.shutdown(wait=False) + return self._handle_error( + f"❌ {tag} Vertex AI API error : {type(e).__name__} : {e}", _batch_idx + ) + _tex.shutdown(wait=False) + + if not response.candidates: + _pf = getattr(response, 'prompt_feedback', None) + _br = getattr(_pf, 'block_reason', None) if _pf else None + _detail = f" | block_reason={_br}" if _br else "" + if _pf: + print(f"🔍 {tag} prompt_feedback={_pf}") + return self._handle_error( + f"❌ {tag} No candidates retourné par Vertex AI{_detail}", _batch_idx + ) + + cand = response.candidates[0] + if ( + hasattr(cand, "finish_reason") + and cand.finish_reason != types.FinishReason.STOP + ): + return self._handle_error( + f"❌ {tag} Generation blocked: finish_reason={cand.finish_reason}", + _batch_idx, + ) + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error( + f"❌ {tag} Aucune donnée image dans la réponse Vertex AI.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _processed2 = set() + _NB2_OUTER = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUTER): + _processed2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FuturesTE2: + print("⚠️ [Vertex NB2] as_completed timeout — salvage des futures terminés...") + for _f, _i in futures.items(): + if _f in _processed2: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fidx}] Récupéré depuis future terminé") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex NB2 Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex NB2 Batch {_fidx}] Outer timeout — still running") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | bloqué par : {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : Seedream 4.5 Edit\n" + f"Taille : {ws_size} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} lors du polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : GPT Image 2.0\n" + f"Aspect ratio : {aspect_ratio} | Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream Kie ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : Seedream 4.5 Edit\n" + f"Qualité : {quality} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL dans resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Ratio : {aspect_ratio} | Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Seedream FAL ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations GPT Image 2.0 FAL ont failed :\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Modèle : GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Qualité : {gpt2_quality} | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Fal.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _processed = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FuturesTE: + print("⚠️ [Google NB2] as_completed timeout — salvage des futures terminés...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fidx}] Récupéré depuis future terminé") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [NB2 Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [NB2 Batch {_fidx}] Outer timeout — still running") + + if not generated_images: + return self._handle_error( + f"Toutes les générations NB2 ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} erreur(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} En cours"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", bloqué par : {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Requête bloquée par l'API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ Aucune clé API Google configurée !\n" + "→ Connectez un node 'API Keys Loader' et câblez gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] En cours"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] En cours", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — requête bloquée (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"Aucune donnée image (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout après {GOOGLE_TASK_TIMEOUT_S}s (Google SDK non répondu)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Échecs ({len(errors)}) : {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations WaveSpeed ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Modèle : google/{model_label}\n" + f"Résolution : {image_size} | Format : {output_format}\n" + f"Temps inférence : {timing_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + + if ws_api_key: + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] CDN failed ({e}), trying catbox.moe...") + img_buffer.seek(0) + + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed: {e}") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"Toutes les générations Kie.ai ont failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Modèle : {model_label}\n" + f"Résolution : {image_size} | Ratio : {aspect_ratio}\n" + f"Temps : {cost_ms}ms | Total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Détecte les visages dans le tensor d'image 2 et les masque + par un carré noir (YuNet via OpenCV). + Retourne le tensor modifié, ou l'original si OpenCV indisponible. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "et Image 2 (face to swap) sont toutes les deux requises." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Modèle : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Route la génération vidéo vers le bon provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Modèle vidéo inconnu : '{model}'.\n" + f"Modèles disponibles : {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Sélectionnez WAVESPEED, KIE ou FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Sélectionnez WAVESPEED, FAL ou KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Modèles disponibles : {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Le provider '{provider}' ne supporte pas la génération vidéo Veo.\n" + "→ Sélectionnez GOOGLE, VERTEX, WAVESPEED, KIE ou FAL pour utiliser les models Veo." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error lors du lancement de la génération : {type(e).__name__} : {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes vide après download — vérifiez les droits Files API." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de lire la réponse vidéo : {type(e).__name__} : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Génération vidéo Vertex AI via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Initialisation — model={model_id} | ratio={aspect_ratio} | durée={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Credentials invalides : {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} Aucune vidéo dans la réponse.\n" + f"Réponse complète : {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Ni base64 ni gcsUri dans la réponse.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Impossible de télécharger depuis GCS ({gcs_uri}) : {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Upload une vidéo locale vers WaveSpeed (multipart) et retourne l'URL publique. + Si video_ref est déjà une URL (http/https), elle est retournée telle quelle.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error upload vidéo : {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | durée={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Génération failed : [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Impossible d'uploader la vidéo de référence." + ) + print(f"🎞️ {tag} Vidéo référence → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Initialisation — durée={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"premières (start + end) seront utilisées.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "début" if idx == 0 else "fin" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image début uploadée → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} Image fin uploadée → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image début uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} Image fin uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Initialisation — durée={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Image début uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} Image fin uploadée → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Soumission refusée : {data.get('msg', 'erreur inconnue')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Échoué : {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | durée={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connectez une vidéo de référence à l'entrée 'video_reference'." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploadée") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Upload vidéo de référence...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Vidéo référence uploadée → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Vidéo encodée en base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Terminé ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Vidéo téléchargée ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | durée={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} URL vidéo : {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Sauvegarde la vidéo dans temp/ et retourne le tuple standard. + La preview est gérée par le node PreviewImageWithoutMetadata en aval.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Vidéo écrite dans temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(non sauvegardé)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(non sauvegardé)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Modèle : {model_id}\n" + f"Ratio : {aspect_ratio} | Durée : {duration}s | FPS : {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Supprime les métadonnées MP4 en parsant directement les boxes binaires. + Vide l'atom 'udta' (Encoder, copyright…) et efface le manufacturer dans + les boxes 'hdlr' (HandlerVendorID). Aucune dépendance externe requise.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Métadonnées vidéo supprimées (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extrait les frames d'un fichier vidéo via cv2. + max_frames : si fourni, stoppe après N frames (None = tout extraire). + Retourne (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(non sauvegardé)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkc6Ci0gRmFjZSBza2luIGNvbG9yIG1hdGNoZXMgYm9keSBhbmQgbmVjayBleGFjdGx5Ci0gU2FtZSBsaWdodGluZyBkaXJlY3Rpb24sIGNvbG9yIHRlbXBlcmF0dXJlLCBzaGFkb3dzIGFuZCBoaWdobGlnaHRzIGFzIGJvZHkKLSBObyB2aXNpYmxlIHNlYW0gb3IgY29sb3IgZGlmZmVyZW5jZSBhdCBmYWNlL25lY2sganVuY3Rpb24KClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKClNpbWlsYXIgaGFpcnN0eWxlIGZyb20gdGhlIHBpY3R1cmUgMSwgc2FtZSBjbG90aGVzIGZyb20gdGhlIHBpY3R1cmUgMi4KCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBzbW9vdGhpbmcuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbi4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260502_095538_nb_aio_faceswap.js b/aiorbust-ofm-pack-main/_backups/20260502_095538_nb_aio_faceswap.js new file mode 100644 index 0000000000000000000000000000000000000000..6ea4194535fe21d2f79cb0db556b7ade1cfd4dbe --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260502_095538_nb_aio_faceswap.js @@ -0,0 +1,1135 @@ +/** + * NanoBananaAIO — Automation Face Swap UI + Image/Video Mode Toggle + * Bloc visuel distinctif avec toggle ON/OFF, verrouillage des widgets, + * restriction du modèle à NBPro/NB2, et option Breast Refiner. + * + Toggle IMAGE / VIDEO avec support Veo 3 (Google & Vertex). + */ +import { app } from "../../scripts/app.js"; +// ─── Constantes mode vidéo ───────────────────────────────────────────────── +const VIDEO_MODELS = ["Veo 3.1 Lite", "Veo 3.1", "Veo 3.1 Fast", "Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control", "Seedance 2.0"]; +const IMAGE_MODELS_DEFAULT = ["Nano Banana Pro", "Nano Banana 2", "Seedream 4.5", "GPT Image 2.0"]; +const VIDEO_ASPECT_RATIOS = ["16:9", "9:16"]; +const IMAGE_ASPECT_RATIOS = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"]; +const VIDEO_RESOLUTIONS = ["480p", "720p", "1080p", "4K"]; +const KLING30_MODELS = ["Kling 3.0"]; +const IMAGE_RESOLUTIONS = ["1K", "2K", "4K"]; +const SEEDANCE_MODELS = ["Seedance 2.0"]; +// ─── Widgets verrouillés en mode automation ──────────────────────────────── +const LOCKABLE_WIDGETS = [ + "prompt", + "negative_prompt", + "use_search", + "system_instructions", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", +]; +const AUTOMATION_MODELS = ["Nano Banana Pro", "Nano Banana 2"]; +// ─── Helpers ─────────────────────────────────────────────────────────────── +function getWidget(node, name) { + return node.widgets?.find(w => w.name === name); +} +/** Synchronise un widget Python caché avec une valeur JS. */ +function syncNodeWidget(node, name, value) { + const w = getWidget(node, name); + if (w) { + w.value = value; + if (w.callback) w.callback(value); + } +} +/** Masque ou affiche un widget standard (computeSize trick). */ +function setWidgetVisible(node, widgetName, visible) { + const w = getWidget(node, widgetName); + if (!w) return; + if (visible) { + if (w._modeOrigComputeSize !== undefined) { + w.computeSize = w._modeOrigComputeSize; + delete w._modeOrigComputeSize; + } else { + delete w.computeSize; + } + w.disabled = false; + w.hidden = false; + } else { + if (w._modeOrigComputeSize === undefined) { + w._modeOrigComputeSize = w.computeSize; + } + w.computeSize = () => [0, -4]; + w.disabled = true; + w.hidden = true; + } + if (w.inputEl) w.inputEl.style.display = visible ? "" : "none"; + if (w.element) w.element.style.display = visible ? "" : "none"; +} +function setWidgetLocked(node, widgetName, locked) { + const w = getWidget(node, widgetName); + if (!w) return; + w.disabled = locked; + const applyStyle = (el) => { + if (!el || !el.style) return; + el.style.opacity = locked ? "0.3" : "1.0"; + el.style.pointerEvents = locked ? "none" : "auto"; + el.style.filter = locked ? "grayscale(60%)" : "none"; + }; + if (w.inputEl) { + w.inputEl.disabled = locked; + applyStyle(w.inputEl); + // Les widgets multiline (negative_prompt, system_instructions) sont + // wrappés dans un parent
; on applique aussi l'effet dessus. + applyStyle(w.inputEl.parentElement); + } + applyStyle(w.element); +} +/** + * Redirige les événements wheel du container DOM vers le canvas LiteGraph, + * pour que le zoom ComfyUI fonctionne même quand la souris survole un widget DOM. + */ +function forwardWheelToCanvas(el) { + el.addEventListener("wheel", (e) => { + e.preventDefault(); + e.stopPropagation(); + const canvas = app.canvas?.canvas; + if (!canvas) return; + canvas.dispatchEvent(new WheelEvent("wheel", { + bubbles: true, cancelable: true, view: window, + deltaX: e.deltaX, deltaY: e.deltaY, deltaZ: e.deltaZ, deltaMode: e.deltaMode, + clientX: e.clientX, clientY: e.clientY, screenX: e.screenX, screenY: e.screenY, + ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, metaKey: e.metaKey, + })); + }, { passive: false }); +} +/** + * Applique / retire l'état automation au node (verrouille les widgets + * et restreint la liste des modèles à NBPro/NB2). + */ +function applyAutomationState(node, enabled) { + const applyLocks = () => { + for (const name of LOCKABLE_WIDGETS) setWidgetLocked(node, name, enabled); + }; + // Passe immédiate, puis plusieurs passes différées pour rattraper les + // widgets multiline (negative_prompt, system_instructions) dont l'inputEl + // n'est parfois rattaché au DOM qu'après un ou deux frames. + applyLocks(); + requestAnimationFrame(applyLocks); + setTimeout(applyLocks, 100); + setTimeout(applyLocks, 400); + const modelWidget = getWidget(node, "model"); + if (!modelWidget) return; + if (enabled) { + if (modelWidget.options?.values) { + modelWidget.options.values = [...AUTOMATION_MODELS]; + } + if (!AUTOMATION_MODELS.includes(modelWidget.value)) { + modelWidget.value = "Nano Banana Pro"; + if (modelWidget.callback) modelWidget.callback("Nano Banana Pro"); + } + } else { + // Restaurer la liste selon le mode courant — Python déclare image+vidéo + // donc on ne peut plus se fier à _fsOrigValues comme source de vérité. + const correctModels = node._nbIsVideoMode ? VIDEO_MODELS : IMAGE_MODELS_DEFAULT; + if (modelWidget.options?.values) modelWidget.options.values = [...correctModels]; + // S'assurer que la valeur courante est dans la liste restaurée + if (!correctModels.includes(modelWidget.value)) { + modelWidget.value = correctModels[0]; + if (modelWidget.callback) modelWidget.callback(correctModels[0]); + } + } + modelWidget.disabled = false; + app.graph.setDirtyCanvas(true, true); +} +// ─── Sync aspect_ratio : grisé si Kling (any) + WAVESPEED en mode vidéo ──────── +// KLING_MODELS — conservé pour référence future, plus utilisé pour le verrouillage aspect_ratio +// (Kling supporte 16:9 et 9:16, les deux valeurs de VIDEO_ASPECT_RATIOS) +const KLING_MODELS = ["Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"]; +// GPT Image 2.0 — aspect ratios supportés (filtre automatique du dropdown) +const GPT2_ASPECT_RATIOS = ["1:1", "4:3", "3:4", "16:9", "9:16"]; +const GPT2_NEAREST_AR = { + "2:3": "9:16", "3:2": "16:9", "4:5": "3:4", "5:4": "4:3", "21:9": "16:9", +}; +function setupKlingAspectRatioSync(node) { + // Kling supporte 16:9 ET 9:16 — le dropdown est déjà restreint à VIDEO_ASPECT_RATIOS + // en mode vidéo, donc aucun verrouillage supplémentaire n'est nécessaire. + // La fonction reste en place pour compatibilité avec les appels existants. + node._nbSyncKlingAspectRatio = () => {}; +} +// ─── Contraintes de durée par modèle vidéo ──────────────────────────────────── +const DURATION_CONSTRAINTS = { + "Kling 2.6": { min: 5, max: 10, step: 5, tooltip: "⚠️ Kling 2.6 only supports 5s or 10s. Any other value will be rounded automatically." }, + "Kling 3.0": { min: 3, max: 15, step: 1, tooltip: "" }, + "Kling 3.0 Motion Control": { min: 3, max: 15, step: 1, tooltip: "ℹ️ Motion Control: output duration equals the reference video's duration." }, + "Seedance 2.0": { min: 4, max: 15, step: 1, tooltip: "⚠️ Seedance 2.0 : image-to-video uniquement." }, + _veo: { min: 4, max: 8, step: 1, tooltip: "" }, +}; +function getDurationConstraint(model) { + return DURATION_CONSTRAINTS[model] ?? DURATION_CONSTRAINTS._veo; +} + +// ─── Sync video_duration selon le modèle ────────────────────────────────────── +function setupKlingDurationSync(node) { + const modelWidget = getWidget(node, "model"); + const durationWidget = getWidget(node, "video_duration"); + if (!modelWidget || !durationWidget) return; + + /** Clamp une valeur dans [min, max] en respectant step. */ + const clampDuration = (v, { min, max, step }) => { + let clamped = Math.max(min, Math.min(max, parseInt(v) || min)); + // Pour step > 1 (ex. Kling 2.6 : step=5) : snap sur le multiple le plus proche + if (step > 1) { + const steps = Math.round((clamped - min) / step); + clamped = min + steps * step; + } + return Math.max(min, Math.min(max, clamped)); + }; + + /** Recalibre min/max/step et snappe la valeur si besoin. */ + const syncDuration = () => { + if (!node._nbIsVideoMode) return; + const c = getDurationConstraint(modelWidget.value); + if (durationWidget.options) { + durationWidget.options.min = c.min; + durationWidget.options.max = c.max; + durationWidget.options.step = c.step; + } + durationWidget.tooltip = c.tooltip; + const clamped = clampDuration(durationWidget.value, c); + if (durationWidget.value !== clamped) { + durationWidget.value = clamped; + if (durationWidget.callback) durationWidget.callback(clamped); + } + node.setDirtyCanvas(true); + }; + + node._nbSyncKlingDuration = syncDuration; + syncDuration(); + + // Hooker le changement de modèle → recalibrer la durée + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncDuration(); + }; +} +// ─── Sync batch_size selon provider et mode vidéo ───────────────────────── +function setupProviderBatchSync(node) { + const providerWidget = getWidget(node, "provider"); + const batchSizeWidget = getWidget(node, "batch_size"); + if (!providerWidget || !batchSizeWidget) return; + const syncBatchState = () => { + const isVideo = node._nbIsVideoMode === true; + // VERTEX image mode : batch autorisé (multi-projets JSON) + // Seul le mode vidéo verrouille batch_size à 1 + const shouldLock = isVideo; + batchSizeWidget.disabled = shouldLock; + if (shouldLock) batchSizeWidget.value = 1; + node.setDirtyCanvas(true); + }; + // Expose pour que les fonctions activateVideoMode / activateImageMode + // puissent déclencher une resynchronisation sans passer par le callback + // du widget provider. + node._nbSyncBatchState = syncBatchState; + syncBatchState(); + const origCallback = providerWidget.callback; + providerWidget.callback = function (...args) { + if (origCallback) origCallback.apply(this, args); + syncBatchState(); + }; +} +// ─── Sync image_size (résolution) selon le modèle vidéo ───────────────────── +// Seedance 2.0 : 480p / 720p / 1080p (pas de 4K) +// Autres modèles vidéo : 720p / 1080p uniquement (pas de 480p) +function setupVideoResolutionSync(node) { + const modelWidget = getWidget(node, "model"); + const imgSizeWidget = getWidget(node, "image_size"); + if (!modelWidget || !imgSizeWidget) return; + + const syncResolution = () => { + if (!node._nbIsVideoMode) return; + const model = modelWidget.value; + const isSeedance = SEEDANCE_MODELS.includes(model); + const isKling30 = KLING30_MODELS.includes(model); + + let allowedRes, defaultRes; + if (isSeedance) { + allowedRes = ["480p", "720p", "1080p"]; + defaultRes = "720p"; + } else if (isKling30) { + allowedRes = ["720p", "1080p", "4K"]; + defaultRes = "1080p"; + } else { + allowedRes = ["720p", "1080p"]; + defaultRes = "1080p"; + } + + if (imgSizeWidget.options?.values) imgSizeWidget.options.values = [...allowedRes]; + if (!allowedRes.includes(imgSizeWidget.value)) { + imgSizeWidget.value = defaultRes; + if (imgSizeWidget.callback) imgSizeWidget.callback(defaultRes); + } + // Tooltip sur le widget modèle pour indiquer image-to-video uniquement + if (modelWidget.options) { + modelWidget.options.tooltip = isSeedance + ? "⚠️ Image-to-video uniquement" + : ""; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncVideoResolution = syncResolution; + + // Hooker le changement de modèle → recalibrer la résolution + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncResolution(); + }; +} +// ─── Sync aspect_ratio et gpt2_image_quality selon le modèle ───────────── +function setupGPT2Sync(node) { + const modelWidget = getWidget(node, "model"); + const arWidget = getWidget(node, "aspect_ratio"); + if (!modelWidget || !arWidget) return; + + /** Retourne le ratio le plus proche supporté par GPT2. */ + function nearestGPT2AR(value) { + if (GPT2_ASPECT_RATIOS.includes(value)) return value; + return GPT2_NEAREST_AR[value] || "1:1"; + } + + /** Applique ou retire le filtre GPT2 sur le dropdown aspect_ratio. */ + const syncAR = () => { + const isGPT2 = (modelWidget.value === "GPT Image 2.0"); + if (isGPT2) { + if (arWidget.options?.values) arWidget.options.values = [...GPT2_ASPECT_RATIOS]; + const snapped = nearestGPT2AR(arWidget.value); + if (arWidget.value !== snapped) { + arWidget.value = snapped; + if (arWidget.callback) arWidget.callback(snapped); + } + } else { + // Restaure la liste complète selon le mode courant + const fullList = node._nbIsVideoMode ? VIDEO_ASPECT_RATIOS : IMAGE_ASPECT_RATIOS; + if (arWidget.options?.values) arWidget.options.values = [...fullList]; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncGPT2AR = syncAR; + syncAR(); + + // Hooker le changement de modèle + const origCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origCb) origCb.apply(this, args); + syncAR(); + }; +} +// ─── Factorisation des styles des boutons ON/OFF ────────────────────────── +// Évite de dupliquer 8 lignes de style à chaque toggle (Face Swap, Breast +// Refiner, Low Neck). Chaque bouton a sa propre palette "ON". +const TOGGLE_OFF_CSS = { + text: "OFF", + background: "#3a3a3a", + color: "#888", + border: "1.5px solid #666", + boxShadow: "none", +}; +/** + * Applique l'état visuel ON/OFF à un bouton bascule. + * @param {HTMLButtonElement} btn + * @param {boolean} on + * @param {{bg:string, text?:string, border:string, glow:string}} onStyle + */ +function setToggleVisual(btn, on, onStyle) { + if (on) { + btn.textContent = onStyle.text || "ON"; + btn.style.background = onStyle.bg; + btn.style.color = "#fff"; + btn.style.border = `1.5px solid ${onStyle.border}`; + btn.style.boxShadow = `0 0 8px ${onStyle.glow}`; + } else { + btn.textContent = TOGGLE_OFF_CSS.text; + btn.style.background = TOGGLE_OFF_CSS.background; + btn.style.color = TOGGLE_OFF_CSS.color; + btn.style.border = TOGGLE_OFF_CSS.border; + btn.style.boxShadow = TOGGLE_OFF_CSS.boxShadow; + } +} +const FS_ON_STYLE = { bg: "#00c853", border: "#00e676", glow: "rgba(0,200,83,0.5)" }; +const BR_ON_STYLE = { bg: "#c2185b", border: "#f50057", glow: "rgba(245,0,87,0.4)" }; +const LN_ON_STYLE = { bg: "#6a1b9a", border: "#ab47bc", glow: "rgba(171,71,188,0.4)" }; +// CSS de base partagé par les 3 boutons ON/OFF (même taille, même rayon) +const TOGGLE_BTN_BASE_CSS = ` + padding: 4px 18px; + border-radius: 14px; + border: 1.5px solid #666; + background: #3a3a3a; + color: #888; + font-weight: 700; + font-size: 11px; + cursor: pointer; + min-width: 55px; + letter-spacing: 0.5px; + transition: all 0.2s ease; +`; +// ─── Image / Video mode toggle ──────────────────────────────────────────── +function buildModeToggle(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #1565c0; + border-radius: 9px; + padding: 8px 10px 11px 10px; + background: linear-gradient(135deg, + rgba(21,101,192,0.14) 0%, + rgba(79,195,247,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Titre ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ GENERATION MODE"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #4fc3f7; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(79,195,247,0.45); + margin-bottom: 7px; + user-select: none; + transition: color 0.25s, text-shadow 0.25s; + `; + container.appendChild(titleEl); + // ── Séparateur ──────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #1565c0 40%, #1565c0 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Boutons IMAGE / VIDÉO côte à côte ───────────────────────────────── + const btnRow = document.createElement("div"); + btnRow.style.cssText = "display:flex; gap:8px;"; + function makeChoiceBtn(label, active) { + const btn = document.createElement("button"); + btn.textContent = label; + btn.style.cssText = ` + flex: 1; + padding: 6px 4px; + border-radius: 8px; + border: 1.5px solid ${active ? "#4fc3f7" : "#444"}; + background: ${active ? "rgba(79,195,247,0.18)" : "#252525"}; + color: ${active ? "#4fc3f7" : "#555"}; + font-weight: 700; + font-size: 11px; + cursor: pointer; + letter-spacing: 1px; + box-shadow: ${active ? "0 0 7px rgba(79,195,247,0.25)" : "none"}; + transition: all 0.2s ease; + `; + return btn; + } + const imgBtn = makeChoiceBtn("🖼 IMAGES", true); + const vidBtn = makeChoiceBtn("🎬 VIDÉO", false); + btnRow.appendChild(imgBtn); + btnRow.appendChild(vidBtn); + container.appendChild(btnRow); + // ── État ────────────────────────────────────────────────────────────── + let isVideoMode = false; + const GREY_IN_VIDEO = [ + "temperature", "top_p", "negative_prompt", + "fal_safety_tolerance", "fal_enable_web_search", + "use_search", "system_instructions", "batch_size", + "gpt2_image_quality", + ]; + // ── Grise/dégrise le bloc Automation Face Swap ─────────────────────── + function setFaceSwapGreyed(greyed) { + const fsW = node.widgets?.find(w => w.name === "nb_faceswap_automation"); + const el = fsW?.element; + if (!el) return; + el.style.opacity = greyed ? "0.22" : "1"; + el.style.pointerEvents = greyed ? "none" : "auto"; + el.style.filter = greyed ? "grayscale(80%) brightness(0.35)" : "none"; + app.graph.setDirtyCanvas(true, true); + } + function updateCombo(name, newValues, newDefault) { + const w = getWidget(node, name); + if (!w) return; + if (w.options?.values) w.options.values = [...newValues]; + if (!newValues.includes(w.value)) { + w.value = newDefault; + if (w.callback) w.callback(newDefault); + } + } + // ── Visibilité des widgets vidéo-only ───────────────────────────────── + // Ces widgets sont visibles SI ET SEULEMENT SI on est en mode VIDEO. + function updateVideoOnlyWidgets(visible) { + setWidgetVisible(node, "video_duration", visible); + setWidgetVisible(node, "video_generate_audio", visible); + } + function updateVideoDurationVisibility() { updateVideoOnlyWidgets(node._nbIsVideoMode === true); } + node._nbUpdateVideoDuration = updateVideoDurationVisibility; + // ── Activer le mode IMAGE ───────────────────────────────────────────── + function activateImageMode(initial = false) { + isVideoMode = false; + node._nbIsVideoMode = false; + imgBtn.style.border = "1.5px solid #4fc3f7"; + imgBtn.style.background = "rgba(79,195,247,0.18)"; + imgBtn.style.color = "#4fc3f7"; + imgBtn.style.boxShadow = "0 0 7px rgba(79,195,247,0.25)"; + vidBtn.style.border = "1.5px solid #444"; + vidBtn.style.background = "#252525"; + vidBtn.style.color = "#555"; + vidBtn.style.boxShadow = "none"; + container.style.border = "2px solid #1565c0"; + container.style.background = "linear-gradient(135deg, rgba(21,101,192,0.14) 0%, rgba(79,195,247,0.06) 100%)"; + titleEl.style.color = "#4fc3f7"; + titleEl.style.textShadow = "0 0 10px rgba(79,195,247,0.45)"; + // IMAGE_MODELS_DEFAULT = source de vérité (Python déclare image+vidéo + // pour la validation serveur, donc options.values n'est plus fiable) + const modelW = getWidget(node, "model"); + if (modelW) { + const vals = IMAGE_MODELS_DEFAULT; + if (modelW.options?.values) modelW.options.values = [...vals]; + if (!vals.includes(modelW.value)) { + modelW.value = vals[0]; + if (modelW.callback) modelW.callback(vals[0]); + } + if (modelW._imgOrigTooltip !== undefined) { + if (modelW.options) modelW.options.tooltip = modelW._imgOrigTooltip; + delete modelW._imgOrigTooltip; + } + } + updateCombo("aspect_ratio", IMAGE_ASPECT_RATIOS, "1:1"); + updateCombo("image_size", IMAGE_RESOLUTIONS, "2K"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "image_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, false); + // Re-synchronise batch_size et aspect_ratio (Kling) en mode image + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(false), 60); + if (!initial) { + syncNodeWidget(node, "video_mode_enabled", false); + app.graph.setDirtyCanvas(true, true); + } + } + // ── Activer le mode VIDÉO ───────────────────────────────────────────── + function activateVideoMode() { + isVideoMode = true; + node._nbIsVideoMode = true; + vidBtn.style.border = "1.5px solid #ce93d8"; + vidBtn.style.background = "rgba(206,147,216,0.18)"; + vidBtn.style.color = "#ce93d8"; + vidBtn.style.boxShadow = "0 0 7px rgba(206,147,216,0.3)"; + imgBtn.style.border = "1.5px solid #444"; + imgBtn.style.background = "#252525"; + imgBtn.style.color = "#555"; + imgBtn.style.boxShadow = "none"; + container.style.border = "2px solid #6a1b9a"; + container.style.background = "linear-gradient(135deg, rgba(106,27,154,0.14) 0%, rgba(206,147,216,0.06) 100%)"; + titleEl.style.color = "#ce93d8"; + titleEl.style.textShadow = "0 0 10px rgba(206,147,216,0.45)"; + // VIDEO_MODELS = source de vérité — pas de sauvegarde _imgOrigValues + // car options.values contient maintenant image+vidéo côté Python + const modelW = getWidget(node, "model"); + if (modelW) { + if (modelW.options?.values) modelW.options.values = [...VIDEO_MODELS]; + if (!VIDEO_MODELS.includes(modelW.value)) { + modelW.value = VIDEO_MODELS[0]; + if (modelW.callback) modelW.callback(VIDEO_MODELS[0]); + } + if (modelW.options?.tooltip) { + modelW._imgOrigTooltip = modelW.options.tooltip; + modelW.options.tooltip = ""; + } + } + updateCombo("aspect_ratio", VIDEO_ASPECT_RATIOS, "16:9"); + updateCombo("image_size", VIDEO_RESOLUTIONS, "1080p"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "video_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, true); + // Force batch_size = 1, synchronise aspect_ratio, durée et résolution selon le modèle + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + node._nbSyncKlingDuration?.(); + node._nbSyncVideoResolution?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(true), 60); + syncNodeWidget(node, "video_mode_enabled", true); + app.graph.setDirtyCanvas(true, true); + } + // ── Listeners ───────────────────────────────────────────────────────── + imgBtn.addEventListener("click", () => { if (isVideoMode) activateImageMode(); }); + vidBtn.addEventListener("click", () => { if (!isVideoMode) activateVideoMode(); }); + node._modeToggleAPI = { activateImageMode, activateVideoMode }; + // ── État initial SYNCHRONE (mode image par défaut) ──────────────────── + // Masquer video_duration AVANT d'ajouter le DOM widget évite un + // redimensionnement visible du node ~250 ms après le démarrage. + node._nbIsVideoMode = false; + updateVideoOnlyWidgets(false); + // ── Ajout DOM widget ────────────────────────────────────────────────── + const domWidget = node.addDOMWidget( + "nb_mode_toggle", "mode_toggle_div", container, + { serialize: false, hideOnZoom: false } + ); + if (domWidget) domWidget.computeSize = (w) => [w, 95]; + // ── Placer en PREMIER ───────────────────────────────────────────────── + if (domWidget) { + const idx = node.widgets.indexOf(domWidget); + if (idx > 0) { node.widgets.splice(idx, 1); node.widgets.unshift(domWidget); } + app.graph.setDirtyCanvas(true, true); + } + // ── Filtrage initial du dropdown "model" (mode image par défaut) ───── + // On ne fait QUE filtrer la liste — pas d'appel à activateImageMode() + // pour éviter de déclencher des callbacks qui perturbent la visibilité + // des widgets DOM (inputEl créés après le premier rendu). + setTimeout(() => { + const modelW = getWidget(node, "model"); + if (!modelW || node._nbIsVideoMode) return; + if (modelW.options?.values) modelW.options.values = [...IMAGE_MODELS_DEFAULT]; + if (!IMAGE_MODELS_DEFAULT.includes(modelW.value)) modelW.value = IMAGE_MODELS_DEFAULT[0]; + }, 200); + // ── Sync UI ↔ widget "video_mode_enabled" après chargement workflow ── + // Au chargement d'un workflow, ComfyUI restaure la valeur du widget + // caché `video_mode_enabled`, mais la variable locale isVideoMode reste + // à false. Résultat : l'UI montre IMAGES mais le backend reçoit + // video_mode_enabled=true → "Modèle vidéo inconnu : Nano Banana Pro". + // On fixe ça en synchronisant l'UI avec la valeur réelle du widget ~350ms + // après le onNodeCreated (délai suffisant pour que configure() ait injecté + // les valeurs sauvegardées). + setTimeout(() => { + const videoModeWidget = getWidget(node, "video_mode_enabled"); + const savedIsVideo = videoModeWidget?.value === true; + if (savedIsVideo && !node._nbIsVideoMode) { + // Workflow sauvegardé en mode vidéo → bascule l'UI en vidéo + activateVideoMode(); + } else { + // Force explicitement le widget à false pour éviter qu'une + // valeur "truthy" résiduelle (1, "true"…) passe côté Python + syncNodeWidget(node, "video_mode_enabled", false); + } + }, 350); +} +// ─── Automation Face Swap UI ────────────────────────────────────────────── +function buildFaceSwapUI(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #e65c00; + border-radius: 9px; + padding: 9px 10px 16px 10px; + background: linear-gradient(135deg, + rgba(230,92,0,0.13) 0%, + rgba(255,140,0,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Title ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ AUTOMATION FACE SWAP"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #ff8c00; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(255,140,0,0.45); + margin-bottom: 7px; + transition: color 0.25s, text-shadow 0.25s; + user-select: none; + `; + container.appendChild(titleEl); + // ── Separator ───────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #e65c00 40%, #e65c00 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Info hint ───────────────────────────────────────────────────────── + const hintEl = document.createElement("div"); + hintEl.textContent = "ℹ️ Image 1 = reference face · Image 2 = face to swap"; + hintEl.style.cssText = ` + font-size: 10px; + color: #999; + font-style: italic; + text-align: center; + margin-bottom: 8px; + user-select: none; + `; + container.appendChild(hintEl); + // ── Helper pour construire une ligne "label + bouton ON/OFF" ────────── + function makeToggleRow(labelText, tooltip, hidden = false) { + const row = document.createElement("div"); + row.style.cssText = ` + display: ${hidden ? "none" : "flex"}; + align-items: center; + gap: 8px; + ${hidden ? "margin-top: 8px; padding-top: 7px; border-top: 1px solid rgba(230,92,0,0.3);" : ""} + `; + const label = document.createElement("span"); + label.textContent = labelText; + label.title = tooltip; + label.style.cssText = ` + font-size: 12px; + color: #ccc; + flex: 1; + user-select: none; + `; + const btn = document.createElement("button"); + btn.textContent = "OFF"; + btn.title = tooltip; + btn.style.cssText = TOGGLE_BTN_BASE_CSS; + row.appendChild(label); + row.appendChild(btn); + return { row, btn }; + } + // ── Face Swap toggle ────────────────────────────────────────────────── + const { row: toggleRow, btn: toggleBtn } = makeToggleRow( + "Face Swap", + "Activate to run Automation Face Swap.\nImage 1 = reference face · Image 2 = face to swap", + false + ); + container.appendChild(toggleRow); + // ── Breast Refiner row (hidden until automation ON) ────────────────── + const { row: brRow, btn: brBtn } = makeToggleRow( + "Breast Refiner", + "This tool enhances breast shape by defining the upper curve for a more natural look. May trigger NSFW restrictions.", + true + ); + container.appendChild(brRow); + // ── Low Neck row (hidden until automation ON) ──────────────────────── + const { row: lnRow, btn: lnBtn } = makeToggleRow( + "Low Neck", + "Add a low neck, might be flagged as sensitive content.", + true + ); + container.appendChild(lnRow); + // ── Facial Expression section (hidden until automation ON) ─────────── + const EXPRESSIONS = [ + "Neutral", "Sensual", "Playful", "Subtle smile", "Smile", "Laugh", + ]; + const exprSection = document.createElement("div"); + exprSection.style.cssText = ` + display: none; + flex-direction: column; + gap: 6px; + margin-top: 8px; + padding-top: 7px; + border-top: 1px solid rgba(230,92,0,0.3); + `; + const exprTitleEl = document.createElement("div"); + exprTitleEl.textContent = "Facial Expression"; + exprTitleEl.style.cssText = ` + font-size: 11px; + font-weight: 600; + color: #aaa; + letter-spacing: 0.8px; + user-select: none; + `; + exprSection.appendChild(exprTitleEl); + const exprGrid = document.createElement("div"); + exprGrid.style.cssText = ` + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 4px; + `; + const exprBtns = {}; + function selectExpression(value) { + for (const [v, btn] of Object.entries(exprBtns)) { + const active = (v === value); + btn.style.background = active ? "rgba(255,140,0,0.35)" : "#2a2a2a"; + btn.style.color = active ? "#ff8c00" : "#888"; + btn.style.border = active ? "1.5px solid #e65c00" : "1.5px solid #444"; + btn.style.fontWeight = active ? "700" : "400"; + } + syncNodeWidget(node, "face_expression", value); + } + for (const value of EXPRESSIONS) { + const btn = document.createElement("button"); + btn.textContent = value; + btn.style.cssText = ` + padding: 4px 6px; + border-radius: 10px; + border: 1.5px solid #444; + background: #2a2a2a; + color: #888; + font-size: 10.5px; + cursor: pointer; + transition: all 0.15s ease; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; + btn.addEventListener("click", () => selectExpression(value)); + exprBtns[value] = btn; + exprGrid.appendChild(btn); + } + exprSection.appendChild(exprGrid); + container.appendChild(exprSection); + selectExpression("Neutral"); + // ── State ───────────────────────────────────────────────────────────── + let automationActive = false; + let breastRefinerActive = false; + let lowNeckActive = false; + const FS_HEIGHT_OFF = 115; + const FS_HEIGHT_ON = 300; + let _blockH = FS_HEIGHT_OFF; + // ── Face Swap toggle ────────────────────────────────────────────────── + toggleBtn.addEventListener("click", () => { + automationActive = !automationActive; + _blockH = automationActive ? FS_HEIGHT_ON : FS_HEIGHT_OFF; + setToggleVisual(toggleBtn, automationActive, FS_ON_STYLE); + if (automationActive) { + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + } else { + container.style.border = "2px solid #e65c00"; + container.style.background = "linear-gradient(135deg, rgba(230,92,0,0.13) 0%, rgba(255,140,0,0.06) 100%)"; + titleEl.style.color = "#ff8c00"; + titleEl.style.textShadow = "0 0 10px rgba(255,140,0,0.45)"; + brRow.style.display = "none"; + lnRow.style.display = "none"; + exprSection.style.display = "none"; + // Reset sub-toggles when automation is switched off + if (breastRefinerActive) { + breastRefinerActive = false; + setToggleVisual(brBtn, false, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", false); + } + if (lowNeckActive) { + lowNeckActive = false; + setToggleVisual(lnBtn, false, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", false); + } + } + applyAutomationState(node, automationActive); + syncNodeWidget(node, "face_swap_enabled", automationActive); + // Force la taille immédiatement (pas de latence au premier clic) + const newSize = node.computeSize(); + node.size[0] = Math.max(node.size[0], newSize[0]); + node.size[1] = newSize[1]; + app.graph.setDirtyCanvas(true, true); + }); + // ── Breast Refiner toggle ───────────────────────────────────────────── + brBtn.addEventListener("click", () => { + breastRefinerActive = !breastRefinerActive; + setToggleVisual(brBtn, breastRefinerActive, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", breastRefinerActive); + app.graph.setDirtyCanvas(true); + }); + // ── Low Neck toggle ─────────────────────────────────────────────────── + lnBtn.addEventListener("click", () => { + lowNeckActive = !lowNeckActive; + setToggleVisual(lnBtn, lowNeckActive, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", lowNeckActive); + app.graph.setDirtyCanvas(true); + }); + // ── Add DOM widget to node ──────────────────────────────────────────── + const domWidget = node.addDOMWidget("nb_faceswap_automation", "automation_div", container, { + serialize: false, + hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + // ── Restaure l'état sauvegardé dans le workflow ─────────────────────── + // Le DOM démarre à OFF par défaut ; on le réaligne sur les widgets Python + // pour que l'état visuel corresponde toujours à ce qui sera exécuté. + const _savedFS = getWidget(node, "face_swap_enabled")?.value === true; + if (_savedFS) { + automationActive = true; + _blockH = FS_HEIGHT_ON; + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + setToggleVisual(toggleBtn, true, FS_ON_STYLE); + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + applyAutomationState(node, true); + } + // Breast Refiner et Low Neck : toujours OFF au démarrage. + // On réinitialise le widget Python même si le workflow les avait sauvegardés + // à true, pour éviter qu'ils se réactivent silencieusement entre sessions. + syncNodeWidget(node, "breast_refiner_enabled", false); + syncNodeWidget(node, "low_neck_enabled", false); + // breastRefinerActive et lowNeckActive restent false, boutons restent OFF. + // Masque les widgets Python cachés (IMMÉDIATEMENT, pas en setTimeout, pour + // éviter que le node soit dessiné grand puis rétréci juste après). + const HIDDEN_PY_WIDGETS = [ + "face_swap_enabled", "breast_refiner_enabled", "low_neck_enabled", + "face_expression", "video_mode_enabled", + ]; + for (const name of HIDDEN_PY_WIDGETS) { + const w = getWidget(node, name); + if (!w) continue; + w._fsOrigComputeSize = w.computeSize; + w.computeSize = () => [0, -4]; + w.hidden = true; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + } + app.graph.setDirtyCanvas(true, true); +} +// ─── Preset panel (10 slots, mode-aware, avec champ nom) ────────────────── +function buildPresetUI(node) { + const NUM_PRESETS = 10; + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #37474f; + border-radius: 9px; + padding: 8px 10px 10px 10px; + background: linear-gradient(135deg, + rgba(55,71,79,0.14) 0%, + rgba(96,125,139,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + `; + forwardWheelToCanvas(container); + const titleEl = document.createElement("div"); + titleEl.textContent = "💾 PRESETS"; + titleEl.style.cssText = ` + font-weight: 700; font-size: 11.5px; color: #90a4ae; + letter-spacing: 2px; text-align: center; + margin-bottom: 7px; user-select: none; + `; + container.appendChild(titleEl); + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #37474f 40%, #37474f 60%, transparent); + opacity: 0.55; margin-bottom: 7px; + `; + container.appendChild(sep); + const list = document.createElement("div"); + list.style.cssText = "display: flex; flex-direction: column; gap: 4px;"; + container.appendChild(list); + const slotRows = {}; + const slotInputs = {}; + function markSlotFilled(n, filled, name) { + const row = slotRows[n]; + const input = slotInputs[n]; + if (!row) return; + row.style.border = filled ? "1px solid rgba(79,195,247,0.3)" : "1px solid #2a2a2a"; + row.style.background = filled ? "rgba(79,195,247,0.04)" : "#1a1a1a"; + if (input && name !== undefined) input.value = name || ""; + } + function buildSlot(n) { + const row = document.createElement("div"); + row.style.cssText = ` + display: flex; align-items: center; gap: 4px; + padding: 3px 5px; border-radius: 6px; + border: 1px solid #2a2a2a; background: #1a1a1a; + transition: border 0.2s, background 0.2s; + `; + slotRows[n] = row; + const label = document.createElement("span"); + label.textContent = `${n < 10 ? " " : ""}${n}`; + label.style.cssText = ` + font-size: 9.5px; color: #555; min-width: 14px; + user-select: none; font-weight: 700; font-variant-numeric: tabular-nums; + `; + const nameInput = document.createElement("input"); + nameInput.type = "text"; + nameInput.placeholder = `preset ${n}`; + nameInput.style.cssText = ` + flex: 1; min-width: 0; + background: #111; border: 1px solid #333; border-radius: 4px; + color: #aaa; font-size: 9.5px; padding: 2px 5px; + outline: none; font-family: 'Segoe UI', Arial, sans-serif; + `; + nameInput.addEventListener("focus", () => nameInput.style.borderColor = "#546e7a"); + nameInput.addEventListener("blur", () => nameInput.style.borderColor = "#333"); + nameInput.addEventListener("keydown", e => e.stopPropagation()); + slotInputs[n] = nameInput; + const btnBase = ` + padding: 2px 8px; border-radius: 4px; font-size: 9px; + font-weight: 700; cursor: pointer; white-space: nowrap; + transition: all 0.15s ease; letter-spacing: 0.4px; + `; + const saveBtn = document.createElement("button"); + saveBtn.textContent = "SAVE"; + saveBtn.title = `Sauvegarder dans le slot ${n}`; + saveBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + const loadBtn = document.createElement("button"); + loadBtn.textContent = "LOAD"; + loadBtn.title = `Charger le slot ${n}`; + loadBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + row.appendChild(label); + row.appendChild(nameInput); + row.appendChild(saveBtn); + row.appendChild(loadBtn); + list.appendChild(row); + saveBtn.addEventListener("click", async () => { + const params = { preset_name: nameInput.value.trim() }; + for (const w of node.widgets || []) { + if (w.name && w.value !== undefined + && w.type !== "button" && w.type !== "dom_widget" + && !w.name.startsWith("nb_")) { + params[w.name] = w.value; + } + } + try { + const res = await fetch("/nb_aio/save_preset", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ slot: n, params }), + }); + const data = await res.json(); + if (data.success) { + markSlotFilled(n, true, params.preset_name); + saveBtn.style.cssText = btnBase + "border:1px solid #00c853; background:#1b5e20; color:#69f0ae;"; + setTimeout(() => { + saveBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + } + } catch (e) { console.error("[NB Presets] Save error:", e); } + }); + loadBtn.addEventListener("click", async () => { + try { + const res = await fetch("/nb_aio/load_presets"); + const data = await res.json(); + if (!data.success) return; + const preset = data.presets?.[String(n)]; + if (!preset) return; + const isVideo = preset.video_mode_enabled === true; + if (isVideo && !node._nbIsVideoMode) { + node._modeToggleAPI?.activateVideoMode(); + } else if (!isVideo && node._nbIsVideoMode) { + node._modeToggleAPI?.activateImageMode(); + } + if (preset.preset_name !== undefined) { + nameInput.value = preset.preset_name || ""; + } + markSlotFilled(n, true, preset.preset_name); + const SKIP = new Set(["video_mode_enabled", "preset_name"]); + for (const [key, value] of Object.entries(preset)) { + if (SKIP.has(key)) continue; + syncNodeWidget(node, key, value); + } + loadBtn.style.cssText = btnBase + "border:1px solid #2962ff; background:#0d47a1; color:#82b1ff;"; + setTimeout(() => { + loadBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + app.graph.setDirtyCanvas(true, true); + } catch (e) { console.error("[NB Presets] Load error:", e); } + }); + } + for (let i = 1; i <= NUM_PRESETS; i++) buildSlot(i); + const PANEL_H = 368; + const domWidget = node.addDOMWidget("nb_presets_ui", "presets_div", container, { + serialize: false, hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, PANEL_H]; + fetch("/nb_aio/load_presets") + .then(r => r.json()) + .then(data => { + if (!data.success) return; + for (let i = 1; i <= NUM_PRESETS; i++) { + const p = data.presets?.[String(i)]; + if (p) markSlotFilled(i, true, p.preset_name); + } + }) + .catch(() => {}); +} +// ─── Prompt widget colour coding ────────────────────────────────────────── +function stylePromptWidgets(node) { + setTimeout(() => { + const pos = getWidget(node, "prompt"); + if (pos?.inputEl) { + pos.inputEl.style.borderLeft = "3px solid #00c853"; + pos.inputEl.style.paddingLeft = "6px"; + pos.inputEl.style.borderRadius = "3px"; + } + const neg = getWidget(node, "negative_prompt"); + if (neg?.inputEl) { + neg.inputEl.style.borderLeft = "3px solid #e53935"; + neg.inputEl.style.paddingLeft = "6px"; + neg.inputEl.style.borderRadius = "3px"; + } + }, 200); +} +// ─── Extension registration ─────────────────────────────────────────────── +app.registerExtension({ + name: "NanoBananaAIO.FaceSwap", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "NanoBananaAIO") return; + const onCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onCreated?.apply(this, arguments); + const node = this; + stylePromptWidgets(node); + // Mode toggle en premier (synchrone) — place le widget tout en haut + buildModeToggle(node); + setTimeout(() => setupKlingAspectRatioSync(node), 500); + setTimeout(() => setupKlingDurationSync(node), 500); + setTimeout(() => setupProviderBatchSync(node), 500); + setTimeout(() => setupGPT2Sync(node), 500); + setTimeout(() => setupVideoResolutionSync(node), 500); + setTimeout(() => buildFaceSwapUI(node), 400); + setTimeout(() => buildPresetUI(node), 450); + // Nettoyage tardif des widgets preset hérités (autre JS) + setTimeout(() => { + if (!node.widgets) return; + const KEEP = new Set([ + "nb_faceswap_automation", "nb_presets_ui", "nb_mode_toggle", + "face_expression", "face_swap_enabled", "breast_refiner_enabled", + "low_neck_enabled", "video_mode_enabled", + ]); + const isLegacy = (w) => { + if (!w.name) return false; + if (KEEP.has(w.name)) return false; + if (w.name.startsWith("nb_")) return false; + const n = w.name.toLowerCase(); + return ( + w.type === "button" || + n.includes("preset") || + n.includes("slot") + ); + }; + for (let i = node.widgets.length - 1; i >= 0; i--) { + const w = node.widgets[i]; + if (!isLegacy(w)) continue; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + node.widgets.splice(i, 1); + } + // Force-hide des widgets Python automation (canvas widgets LiteGraph) + for (const name of ["face_expression", "face_swap_enabled", + "breast_refiner_enabled", "low_neck_enabled", + "video_mode_enabled"]) { + const w = getWidget(node, name); + if (!w) continue; + w.hidden = true; + w.computeSize = () => [0, -4]; + if (w.inputEl) { try { w.inputEl.remove(); } catch (_) {} w.inputEl = null; } + if (w.element) { try { w.element.remove(); } catch (_) {} w.element = null; } + } + app.graph.setDirtyCanvas(true, true); + }, 1200); + }; + }, +}); \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260503_185955_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260503_185955_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..a99be73e60fa5d9e80ac497c27f6df8016dfff92 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260503_185955_nano_banana_aio.py @@ -0,0 +1,6615 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K · video: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 400 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCk5vIGZsb2F0aW5nIGZhY2UgZWZmZWN0IG9yIGluY29ycmVjdCBoZWFkIHBsYWNlbWVudApGYWNlIG11c3QgaW5oZXJpdCB0aGUgc2FtZSBuYXR1cmFsIFJBVyBwaG90byBsb29rIGFzIHRoZSBib2R5CgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkcg4oCUIENSSVRJQ0FMOgoKLSBGYWNlIHNraW4gbXVzdCBwZXJmZWN0bHkgaW5oZXJpdCB0aGUgYm9keSBza2luIHRvbmUsIHVuZGVydG9uZSwgdGV4dHVyZSwgcG9yZXMsIHNoYXJwbmVzcyBhbmQgZHluYW1pYyByYW5nZQotIElkZW50aWNhbCBsaWdodGluZyByZXNwb25zZSBhcyBib2R5OiBzYW1lIHNoYWRvd3MsIGhpZ2hsaWdodHMsIGV4cG9zdXJlLCB3aGl0ZSBiYWxhbmNlIGFuZCBjb2xvciB0ZW1wZXJhdHVyZQotIENvbXBsZXRlbHkgc2VhbWxlc3MgamF3bGluZSBhbmQgbmVjayB0cmFuc2l0aW9uCi0gTm8gc2VhbSwgbm8gaGFsbywgbm8gY29sb3Igc2hpZnQsIG5vIGJyaWdodG5lc3MgbWlzbWF0Y2gsIG5vIHRleHR1cmUgZGlmZmVyZW5jZQotIE5vIHBhc3RlZC1vbiBmYWNlLCBubyBBSSBwYXRjaCBlZmZlY3QsIG5vIOKAnGRpZmZlcmVudCBwaG90b+KAnSBsb29rCi0gRmFjZSBtdXN0IGxvb2sgbmF0dXJhbGx5IGF0dGFjaGVkIHRvIHRoZSBib2R5IGluIG9uZSBzaW5nbGUgdW50b3VjaGVkIFJBVyBwaG90bwoKClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClNpbWlsYXIgaGFpcnN0eWxlIGZyb20gdGhlIHBpY3R1cmUgMSwgc2FtZSBjbG90aGVzIGZyb20gdGhlIHBpY3R1cmUgMi4KCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBzbW9vdGhpbmcuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbiwgbm8gdGV4dCwgbm8gd2F0ZXJtYXJrLCBubyBlbW90aWNvbnMu" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260503_190308_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260503_190308_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..b33fc81235b6187f785e06957064f25aae769854 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260503_190308_nano_banana_aio.py @@ -0,0 +1,6616 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K · video: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = True # active le preview interactif (clic loupe, clic-droit enregistrer) + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 400 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.20) + pad_h = int(fh * 0.20) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = requests.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = requests.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "VXNpbmcgcGljdHVyZSAxIGFzIGZhY2lhbCBhbmQgaGFpciByZWZlcmVuY2Ugb25seSwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIAphIG5ldyBmYWNlIGFuZCBuZXcgaGFpciBvbiB0aGUgYm9keSBvZiB0aGUgZ2lybCBpbiBwaWN0dXJlIDIuCkRvIG5vdCB0cmFuc2ZlciwgY29weSBvciBwYXN0ZSBhbnkgZWxlbWVudCBmcm9tIHBpY3R1cmUgMSBkaXJlY3RseS4KVXNlIHBpY3R1cmUgMSBhcyBhIHZpc3VhbCBndWlkZSB0byB1bmRlcnN0YW5kIHRoZSBmYWNlIHN0cnVjdHVyZSwgCmhhaXIgY29sb3IgYW5kIGhhaXIgbGVuZ3RoIOKAlCB0aGVuIGZyZWVseSByZWdlbmVyYXRlIGV2ZXJ5dGhpbmcgZnJvbSBzY3JhdGNoLgpCbGVuZCB0aGUgcmVnZW5lcmF0ZWQgZmFjZSBhbmQgaGFpciBuYXR1cmFsbHkgd2l0aCB0aGUgYm9keSBvZiBwaWN0dXJlIDIuClRoZSBsaWdodGluZyBvbiB0aGUgZmFjZSBhbmQgaGFpciBtdXN0IHBlcmZlY3RseSBtYXRjaCB0aGUgb3ZlcmFsbCBsaWdodGluZyBvZiBwaWN0dXJlIDIuClNhbWUgZmFjaWFsIHN0cnVjdHVyZSBmcm9tIHBpY3R1cmUgMSwgcGVyZmVjdGx5IHJlY29nbml6YWJsZSBmYWNlLgpHZW5lcmF0ZSBhIE5FVyBmYWNpYWwgZXhwcmVzc2lvbiBuYXR1cmFsbHkgc3VpdGVkIHRvIHRoZSBib2R5IHBvc2UsIG5ldmVyIGNvcHkgdGhlIGV4cHJlc3Npb24gZnJvbSBwaWN0dXJlIDEuCk5vIGZsb2F0aW5nIGZhY2UgZWZmZWN0IG9yIGluY29ycmVjdCBoZWFkIHBsYWNlbWVudApGYWNlIG11c3QgaW5oZXJpdCB0aGUgc2FtZSBuYXR1cmFsIFJBVyBwaG90byBsb29rIGFzIHRoZSBib2R5CgpDUklTUFkgUkFXIFBIT1RPIHF1YWxpdHksIE5PIGNvbGxhZ2UgYXBwZWFyYW5jZS4KU2VhbWxlc3MgZmFjZSBpbnRlZ3JhdGlvbiB3aXRoIGNsZWFuIGVkZ2UgYmxlbmRpbmcuCgpQRVJGRUNUIFNLSU4gTUFUQ0hJTkcg4oCUIENSSVRJQ0FMOgoKLSBGYWNlIHNraW4gbXVzdCBwZXJmZWN0bHkgaW5oZXJpdCB0aGUgYm9keSBza2luIHRvbmUsIHVuZGVydG9uZSwgdGV4dHVyZSwgcG9yZXMsIHNoYXJwbmVzcyBhbmQgZHluYW1pYyByYW5nZQotIElkZW50aWNhbCBsaWdodGluZyByZXNwb25zZSBhcyBib2R5OiBzYW1lIHNoYWRvd3MsIGhpZ2hsaWdodHMsIGV4cG9zdXJlLCB3aGl0ZSBiYWxhbmNlIGFuZCBjb2xvciB0ZW1wZXJhdHVyZQotIENvbXBsZXRlbHkgc2VhbWxlc3MgamF3bGluZSBhbmQgbmVjayB0cmFuc2l0aW9uCi0gTm8gc2VhbSwgbm8gaGFsbywgbm8gY29sb3Igc2hpZnQsIG5vIGJyaWdodG5lc3MgbWlzbWF0Y2gsIG5vIHRleHR1cmUgZGlmZmVyZW5jZQotIE5vIHBhc3RlZC1vbiBmYWNlLCBubyBBSSBwYXRjaCBlZmZlY3QsIG5vIOKAnGRpZmZlcmVudCBwaG90b+KAnSBsb29rCi0gRmFjZSBtdXN0IGxvb2sgbmF0dXJhbGx5IGF0dGFjaGVkIHRvIHRoZSBib2R5IGluIG9uZSBzaW5nbGUgdW50b3VjaGVkIFJBVyBwaG90bwoKClBFUkZFQ1QgU0laRToKLSBGYWNlIHN0cmljdGx5IG1hdGNoZXMgbmVjayB3aWR0aCAoc21hbGwgYW5kIHJlYWxpc3RpYykKLSBIZWFkIG5ldmVyIGV4Y2VlZHMgMTo3IGhlYWQtdG8tYm9keSByYXRpbwotIFByZWZlciBzbGlnaHRseSBzbWFsbGVyIGZhY2UgaWYgdW5jZXJ0YWluCgpOTyBDT1BZLCBOTyBQQVNURSwgTk8gQ1VUT1VULCBOTyBMQVlFUiBvZiB0aGUgcmVmZXJlbmNlIGZhY2UuCkFsd2F5cyByZWludGVycHJldCwgcmVkcmF3IGFuZCByZWdlbmVyYXRlIHRoZSBmYWNlIGNvbXBsZXRlbHkgZnJvbSBzY3JhdGNoLgpUaGUgcmVmZXJlbmNlIGlzIGEgZ3VpZGUgb25seSwgbmV2ZXIgYSBzb3VyY2UgdG8gY29weS4KVGhlIGV4cHJlc3Npb24sIGFuZ2xlIGFuZCBsaWdodGluZyBtdXN0IGJlIG5hdHVyYWxseSBhZGFwdGVkLCBuZXZlciBkdXBsaWNhdGVkLgoKSEFJUiDigJQgQ1JJVElDQUw6Ci0gSGFpciBjb2xvciBhbmQgbGVuZ3RoIGZyb20gcGljdHVyZSAxIGFzIGluc3BpcmF0aW9uIG9ubHkKLSBORVZFUiByZXByb2R1Y2UgdGhlIGV4YWN0IGhhaXIgcGFydCwgaGFpciBwb3NpdGlvbiBvciBoYWlyIHN0cmFuZHMgZnJvbSBwaWN0dXJlIDEKLSBJZ25vcmUgY29tcGxldGVseSB0aGUgY2VudGVyIHBhcnQgLyBoYWlyIHNlcGFyYXRpb24gdmlzaWJsZSBpbiBwaWN0dXJlIDEKLSBGcmVlbHkgcmVpbWFnaW5lIHRoZSBoYWlyc3R5bGUgYWRhcHRlZCB0byB0aGUgaGVhZCBhbmdsZSBhbmQgbGlnaHRpbmcgb2YgcGljdHVyZSAyCi0gR2VuZXJhdGUgb3JnYW5pYywgbmF0dXJhbGx5IGZsb3dpbmcgaGFpciBhcyBpZiBmcmVzaGx5IHBob3RvZ3JhcGhlZAotIEV2ZXJ5IHN0cmFuZCBuYXR1cmFsbHkgZ2VuZXJhdGVkLCBuZXZlciBjb3BpZWQgb3IgbWlycm9yZWQgZnJvbSByZWZlcmVuY2UKLSBOTyBibHVyLCBOTyBmZWF0aGVyaW5nLCBOTyBtYXNrIHNtb290aGluZyBvbiBoYWlyIGJvcmRlcnMKLSBDb21wbGV0ZWx5IGlnbm9yZSBhbmQgZXJhc2UgYWxsIGhhaXIgZnJvbSBwaWN0dXJlIDIKLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClNpbWlsYXIgaGFpcnN0eWxlIGZyb20gdGhlIHBpY3R1cmUgMSwgc2FtZSBjbG90aGVzIGZyb20gdGhlIHBpY3R1cmUgMi4KCkNhbWVyYS9sb29rOiBEU0xSLXJhdyBjcmlzcG5lc3MsIHNoYXJwIGZvY3VzLCBubyBzbW9vdGhpbmcuIENyaXNwIHNraW4gdGV4dHVyZSwgbGlnaHQgbmF0dXJhbCBzZW5zb3IgZ3JhaW4uIFVMVFJBIERFVEFJTEVEIFNLSU4gVEVYVFVSRSB3aXRoIHZpc2libGUgcG9yZXMsIE5PIEFDTkUsIHBhcyBkZSBib3V0b25zLCBFWFRSRU1FIERFVEFJTCwgTmF0aXZlIDhLIHJlc29sdXRpb24uIFBob3RvcmVhbGlzbSwgQWRkIGEgdmVyeSBzdWJ0bGUgZmlsbSBncmFpbiwgbm8gdGV4dCwgbm8gd2F0ZXJtYXJrLCBubyBlbW90aWNvbnMu" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) diff --git a/aiorbust-ofm-pack-main/_backups/20260504_183830_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260504_183830_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..ecae028e30ceb50b725ffb79dd994869c87d8e64 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260504_183830_nano_banana_aio.py @@ -0,0 +1,6657 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Shared session for all KIE requests — reuses TCP connection + looks like a browser +_kie_session = requests.Session() +_kie_session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) +}) + +# KIE session with automatic retry on connection errors (RemoteDisconnected, etc.) +def _make_kie_session() -> "requests.Session": + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + session = requests.Session() + retry = Retry( + total=4, # up to 4 total attempts + connect=4, # retry on connection errors (RemoteDisconnected) + read=2, # retry on read errors + backoff_factor=1.5, # 1.5s, 2.25s, 3.4s between retries + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["POST", "GET"], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("https://", adapter) + session.mount("http://", adapter) + session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) + }) + return session + +_kie_session = _make_kie_session() + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K · video: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "1:1"}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = False + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + + + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 300 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0, "includeThoughts": False}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.30) + pad_h = int(fh * 0.30) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = _kie_session.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "UGljdHVyZSAxIGRlZmluZXMgdGhlIGlkZW50aXR5LCBmYWNpYWwgYW5hdG9teSBhbmQgaGFpciBjaGFyYWN0ZXJpc3RpY3Mgb2YgdGhlIHN1YmplY3QuCk1haW50YWluIHRoZSBwb3NlLCBmcmFtaW5nLCBjbG90aGluZyBhbmQgZW52aXJvbm1lbnQgZnJvbSBwaWN0dXJlIDIuCkdlbmVyYXRlIGEgbmV3bHkgcmVjb25zdHJ1Y3RlZCB2ZXJzaW9uIG9mIHRoZSBzdWJqZWN0IGZyb20gcGljdHVyZSAxIG5hdHVyYWxseSBwaG90b2dyYXBoZWQgaW4gdGhlIHNjZW5lLCBwb3NlIGFuZCBjYW1lcmEgZnJhbWluZyBvZiBwaWN0dXJlIDIuClVzZSBwaWN0dXJlIDEgYXMgYSB2aXN1YWwgZ3VpZGUgdG8gdW5kZXJzdGFuZCB0aGUgZmFjZSBzdHJ1Y3R1cmUsIApoYWlyIGNvbG9yIGFuZCBoYWlyIGxlbmd0aCDigJQgdGhlbiBmcmVlbHkgcmVnZW5lcmF0ZSBldmVyeXRoaW5nIGZyb20gc2NyYXRjaC4KVGhlIHN1YmplY3QgbXVzdCBsb29rIGxpa2UgYSBzaW5nbGUgbmF0dXJhbGx5IHBob3RvZ3JhcGhlZCBwZXJzb24gY2FwdHVyZWQgaW4tY2FtZXJhLgpUaGUgbGlnaHRpbmcgb24gdGhlIGZhY2UgYW5kIGhhaXIgbXVzdCBwZXJmZWN0bHkgbWF0Y2ggdGhlIG92ZXJhbGwgbGlnaHRpbmcgb2YgcGljdHVyZSAyLgpQcmVzZXJ2ZSB0aGUgaWRlbnRpdHkgY29uc2lzdGVuY3kgYW5kIGZhY2lhbCBwcm9wb3J0aW9ucyBkZWZpbmVkIGJ5IHBpY3R1cmUgMS4KR2VuZXJhdGUgYSBORVcgZmFjaWFsIGV4cHJlc3Npb24gbmF0dXJhbGx5IHN1aXRlZCB0byB0aGUgYm9keSBwb3NlLCBuZXZlciBjb3B5IHRoZSBleHByZXNzaW9uIGZyb20gcGljdHVyZSAxLgpObyBmbG9hdGluZyBmYWNlIGVmZmVjdCBvciBpbmNvcnJlY3QgaGVhZCBwbGFjZW1lbnQKRmFjZSBtdXN0IGluaGVyaXQgdGhlIHNhbWUgbmF0dXJhbCBSQVcgcGhvdG8gbG9vayBhcyB0aGUgYm9keQoKQ1JJU1BZIFJBVyBQSE9UTyBxdWFsaXR5LgpIZWFkLCBuZWNrIGFuZCBib2R5IG11c3Qgc2hhcmUgaWRlbnRpY2FsIHBlcnNwZWN0aXZlLCBsaWdodGluZyBhbmQgcGhvdG9ncmFwaGljIGNoYXJhY3RlcmlzdGljcywgd2l0aCBjbGVhbiBlZGdlIGJsZW5kaW5nLgoKUEVSRkVDVCBTS0lOIE1BVENISU5HIOKAlCBDUklUSUNBTDoKCi0gRmFjZSBza2luIG11c3QgcGVyZmVjdGx5IGluaGVyaXQgdGhlIGJvZHkgc2tpbiB0b25lLCB1bmRlcnRvbmUsIHRleHR1cmUsIHBvcmVzLCBzaGFycG5lc3MgYW5kIGR5bmFtaWMgcmFuZ2UKLSBJZGVudGljYWwgbGlnaHRpbmcgcmVzcG9uc2UgYXMgYm9keTogc2FtZSBzaGFkb3dzLCBoaWdobGlnaHRzLCBleHBvc3VyZSwgd2hpdGUgYmFsYW5jZSBhbmQgY29sb3IgdGVtcGVyYXR1cmUKLSBDb21wbGV0ZWx5IHNlYW1sZXNzIGphd2xpbmUgYW5kIG5lY2sgdHJhbnNpdGlvbgotIE5vIHNlYW0sIG5vIGhhbG8sIG5vIGNvbG9yIHNoaWZ0LCBubyBicmlnaHRuZXNzIG1pc21hdGNoLCBubyB0ZXh0dXJlIGRpZmZlcmVuY2UKLSBDb25zaXN0ZW50IHBob3RvZ3JhcGhpYyBjb2hlcmVuY2UgYWNyb3NzIHRoZSBlbnRpcmUgc3ViamVjdC4KLSBGYWNlIG11c3QgbG9vayBuYXR1cmFsbHkgYXR0YWNoZWQgdG8gdGhlIGJvZHkgaW4gb25lIHNpbmdsZSB1bnRvdWNoZWQgUkFXIHBob3RvCgoKUEVSRkVDVCBIRUFEIFNDQUxFIOKAlCBDUklUSUNBTDoKCi0gSGVhZCBzaXplIG11c3QgcmVtYWluIGFuYXRvbWljYWxseSBwcm9wb3J0aW9uYWwgdG8gdGhlIGJvZHkgYW5kIGNhbWVyYSBwZXJzcGVjdGl2ZQotIEhlYWQgbXVzdCBORVZFUiBhcHBlYXIgb3ZlcnNpemVkIHJlbGF0aXZlIHRvIHNob3VsZGVycywgbmVjayBvciB0b3JzbwotIEZhY2Ugd2lkdGggbXVzdCBzdGF5IG5hdHVyYWxseSBhbGlnbmVkIHdpdGggbmVjayB3aWR0aAotIE1haW50YWluIHJlYWxpc3RpYyBkaXN0YW5jZSBiZXR3ZWVuIGNoaW4sIHNob3VsZGVycyBhbmQgdXBwZXIgdG9yc28KLSBJZiB1bmNlcnRhaW4sIEFMV0FZUyBwcmVmZXIgYSBzbGlnaHRseSBzbWFsbGVyIGhlYWQgc2l6ZQotIEF2b2lkIGVubGFyZ2VkIGZhY2lhbCBwcm9wb3J0aW9ucywgem9vbWVkLWluIGZhY2UgcmVuZGVyaW5nIG9yIGV4YWdnZXJhdGVkIGhlYWQgc2NhbGUKCgpIQUlSIOKAlCBDUklUSUNBTDoKLSBIYWlyIGNvbG9yIGFuZCBsZW5ndGggZnJvbSBwaWN0dXJlIDEgYXMgaW5zcGlyYXRpb24gb25seQotIE5FVkVSIHJlcHJvZHVjZSB0aGUgZXhhY3QgaGFpciBwYXJ0LCBoYWlyIHBvc2l0aW9uIG9yIGhhaXIgc3RyYW5kcyBmcm9tIHBpY3R1cmUgMQotIElnbm9yZSBjb21wbGV0ZWx5IHRoZSBjZW50ZXIgcGFydCAvIGhhaXIgc2VwYXJhdGlvbiB2aXNpYmxlIGluIHBpY3R1cmUgMQotIEZyZWVseSByZWltYWdpbmUgdGhlIGhhaXJzdHlsZSBhZGFwdGVkIHRvIHRoZSBoZWFkIGFuZ2xlIGFuZCBsaWdodGluZyBvZiBwaWN0dXJlIDIKLSBHZW5lcmF0ZSBvcmdhbmljLCBuYXR1cmFsbHkgZmxvd2luZyBoYWlyIGFzIGlmIGZyZXNobHkgcGhvdG9ncmFwaGVkCi0gRXZlcnkgc3RyYW5kIG5hdHVyYWxseSBnZW5lcmF0ZWQsIG5ldmVyIGNvcGllZCBvciBtaXJyb3JlZCBmcm9tIHJlZmVyZW5jZQotIEZ1bGx5IHJlZ2VuZXJhdGUgdGhlIGhhaXJzdHlsZSB3aXRoIG5vIGluZmx1ZW5jZSBmcm9tIHRoZSBvcmlnaW5hbCBoYWlyIGluIHBpY3R1cmUgMi4KLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClRoZSBmaW5hbCByZXN1bHQgbXVzdCBsb29rIGxpa2UgYSBjb21wbGV0ZWx5IG5ldyBvcmlnaW5hbCBwaG90b2dyYXBoIG9mIGEgc2luZ2xlIHJlYWwgcGVyc29uLCBuYXR1cmFsbHkgY2FwdHVyZWQgaW4tY2FtZXJhIHVuZGVyIG9uZSBjb25zaXN0ZW50IGxpZ2h0aW5nIHNldHVwIGFuZCBvbmUgY29uc2lzdGVudCBjYW1lcmEgcGVyc3BlY3RpdmUuCgpBdm9pZCBhbnkgaW1wcmVzc2lvbiBvZiBjb21wb3NpdGluZywgZmFjaWFsIHJlcGxhY2VtZW50LCBsYXllcmVkIGdlbmVyYXRpb24sIG9yIGluZGVwZW5kZW50bHkgcmVuZGVyZWQgZmFjaWFsIHJlZ2lvbnMuCgpUaGUgZW50aXJlIHN1YmplY3QgbXVzdCBzaGFyZSB0aGUgc2FtZSBwaG90b2dyYXBoaWMgY29oZXJlbmNlLCBsZW5zIGNoYXJhY3RlcmlzdGljcywgcGVyc3BlY3RpdmUgZGVwdGgsIHNraW4gcmVuZGVyaW5nIGFuZCBsaWdodGluZyBiZWhhdmlvci4KCgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDEsIHNhbWUgY2xvdGhlcyBmcm9tIHRoZSBwaWN0dXJlIDIuCgpDYW1lcmEvbG9vazogRFNMUi1yYXcgY3Jpc3BuZXNzLCBzaGFycCBmb2N1cywgbm8gc21vb3RoaW5nLiBDcmlzcCBza2luIHRleHR1cmUsIGxpZ2h0IG5hdHVyYWwgc2Vuc29yIGdyYWluLiBVTFRSQSBERVRBSUxFRCBTS0lOIFRFWFRVUkUgd2l0aCB2aXNpYmxlIHBvcmVzLCBOTyBBQ05FLCBwYXMgZGUgYm91dG9ucywgRVhUUkVNRSBERVRBSUwsIE5hdGl2ZSA4SyByZXNvbHV0aW9uLiBQaG90b3JlYWxpc20sIEFkZCBhIHZlcnkgc3VidGxlIGZpbG0gZ3JhaW4sIG5vIGVtb3RpY29ucy4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260505_144813_nb_aio_faceswap.js b/aiorbust-ofm-pack-main/_backups/20260505_144813_nb_aio_faceswap.js new file mode 100644 index 0000000000000000000000000000000000000000..9807372d62d8d28234d0e54c105f50f69f891ac1 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260505_144813_nb_aio_faceswap.js @@ -0,0 +1,1171 @@ +/** + * NanoBananaAIO — Automation Face Swap UI + Image/Video Mode Toggle + * Bloc visuel distinctif avec toggle ON/OFF, verrouillage des widgets, + * restriction du modèle à NBPro/NB2, et option Breast Refiner. + * + Toggle IMAGE / VIDEO avec support Veo 3 (Google & Vertex). + */ +import { app } from "../../scripts/app.js"; +// ─── Constantes mode vidéo ───────────────────────────────────────────────── +const VIDEO_MODELS = ["Veo 3.1 Lite", "Veo 3.1", "Veo 3.1 Fast", "Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control", "Seedance 2.0"]; +const IMAGE_MODELS_DEFAULT = ["Nano Banana Pro", "Nano Banana 2", "Seedream 4.5", "GPT Image 2.0"]; +const VIDEO_ASPECT_RATIOS = ["16:9", "9:16"]; +const IMAGE_ASPECT_RATIOS = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"]; +const VIDEO_RESOLUTIONS = ["480p", "720p", "1080p", "4K"]; +const KLING30_MODELS = ["Kling 3.0"]; +const IMAGE_RESOLUTIONS = ["1K", "2K", "4K"]; +const SEEDANCE_MODELS = ["Seedance 2.0"]; +// ─── Widgets verrouillés en mode automation ──────────────────────────────── +const LOCKABLE_WIDGETS = [ + "prompt", + "negative_prompt", + "use_search", + "system_instructions", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", +]; +const AUTOMATION_MODELS = ["Nano Banana Pro", "Nano Banana 2"]; +// ─── Helpers ─────────────────────────────────────────────────────────────── +function getWidget(node, name) { + return node.widgets?.find(w => w.name === name); +} +/** Synchronise un widget Python caché avec une valeur JS. */ +function syncNodeWidget(node, name, value) { + const w = getWidget(node, name); + if (w) { + w.value = value; + if (w.callback) w.callback(value); + } +} +/** Masque ou affiche un widget standard (computeSize trick). */ +function setWidgetVisible(node, widgetName, visible) { + const w = getWidget(node, widgetName); + if (!w) return; + if (visible) { + if (w._modeOrigComputeSize !== undefined) { + w.computeSize = w._modeOrigComputeSize; + delete w._modeOrigComputeSize; + } else { + delete w.computeSize; + } + w.disabled = false; + w.hidden = false; + } else { + if (w._modeOrigComputeSize === undefined) { + w._modeOrigComputeSize = w.computeSize; + } + w.computeSize = () => [0, -4]; + w.disabled = true; + w.hidden = true; + } + if (w.inputEl) w.inputEl.style.display = visible ? "" : "none"; + if (w.element) w.element.style.display = visible ? "" : "none"; +} +function setWidgetLocked(node, widgetName, locked) { + const w = getWidget(node, widgetName); + if (!w) return; + w.disabled = locked; + const applyStyle = (el) => { + if (!el || !el.style) return; + el.style.opacity = locked ? "0.3" : "1.0"; + el.style.pointerEvents = locked ? "none" : "auto"; + el.style.filter = locked ? "grayscale(60%)" : "none"; + }; + if (w.inputEl) { + w.inputEl.disabled = locked; + applyStyle(w.inputEl); + // Les widgets multiline (negative_prompt, system_instructions) sont + // wrappés dans un parent
; on applique aussi l'effet dessus. + applyStyle(w.inputEl.parentElement); + } + applyStyle(w.element); +} +/** + * Redirige les événements wheel du container DOM vers le canvas LiteGraph, + * pour que le zoom ComfyUI fonctionne même quand la souris survole un widget DOM. + */ +function forwardWheelToCanvas(el) { + el.addEventListener("wheel", (e) => { + e.preventDefault(); + e.stopPropagation(); + const canvas = app.canvas?.canvas; + if (!canvas) return; + canvas.dispatchEvent(new WheelEvent("wheel", { + bubbles: true, cancelable: true, view: window, + deltaX: e.deltaX, deltaY: e.deltaY, deltaZ: e.deltaZ, deltaMode: e.deltaMode, + clientX: e.clientX, clientY: e.clientY, screenX: e.screenX, screenY: e.screenY, + ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, metaKey: e.metaKey, + })); + }, { passive: false }); +} +/** + * Applique / retire l'état automation au node (verrouille les widgets + * et restreint la liste des modèles à NBPro/NB2). + */ +function applyAutomationState(node, enabled) { + const applyLocks = () => { + for (const name of LOCKABLE_WIDGETS) setWidgetLocked(node, name, enabled); + }; + // Passe immédiate, puis plusieurs passes différées pour rattraper les + // widgets multiline (negative_prompt, system_instructions) dont l'inputEl + // n'est parfois rattaché au DOM qu'après un ou deux frames. + applyLocks(); + requestAnimationFrame(applyLocks); + setTimeout(applyLocks, 100); + setTimeout(applyLocks, 400); + const modelWidget = getWidget(node, "model"); + if (!modelWidget) return; + if (enabled) { + if (modelWidget.options?.values) { + modelWidget.options.values = [...AUTOMATION_MODELS]; + } + if (!AUTOMATION_MODELS.includes(modelWidget.value)) { + modelWidget.value = "Nano Banana Pro"; + if (modelWidget.callback) modelWidget.callback("Nano Banana Pro"); + } + } else { + // Restaurer la liste selon le mode courant — Python déclare image+vidéo + // donc on ne peut plus se fier à _fsOrigValues comme source de vérité. + const correctModels = node._nbIsVideoMode ? VIDEO_MODELS : IMAGE_MODELS_DEFAULT; + if (modelWidget.options?.values) modelWidget.options.values = [...correctModels]; + // S'assurer que la valeur courante est dans la liste restaurée + if (!correctModels.includes(modelWidget.value)) { + modelWidget.value = correctModels[0]; + if (modelWidget.callback) modelWidget.callback(correctModels[0]); + } + } + modelWidget.disabled = false; + app.graph.setDirtyCanvas(true, true); +} +// ─── Sync aspect_ratio : grisé si Kling (any) + WAVESPEED en mode vidéo ──────── +// KLING_MODELS — conservé pour référence future, plus utilisé pour le verrouillage aspect_ratio +// (Kling supporte 16:9 et 9:16, les deux valeurs de VIDEO_ASPECT_RATIOS) +const KLING_MODELS = ["Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"]; +// GPT Image 2.0 — aspect ratios supportés (filtre automatique du dropdown) +const GPT2_ASPECT_RATIOS = ["1:1", "4:3", "3:4", "16:9", "9:16"]; +const GPT2_NEAREST_AR = { + "2:3": "9:16", "3:2": "16:9", "4:5": "3:4", "5:4": "4:3", "21:9": "16:9", +}; +function setupKlingAspectRatioSync(node) { + // Kling supporte 16:9 ET 9:16 — le dropdown est déjà restreint à VIDEO_ASPECT_RATIOS + // en mode vidéo, donc aucun verrouillage supplémentaire n'est nécessaire. + // La fonction reste en place pour compatibilité avec les appels existants. + node._nbSyncKlingAspectRatio = () => {}; +} +// ─── Contraintes de durée par modèle vidéo ──────────────────────────────────── +const DURATION_CONSTRAINTS = { + "Kling 2.6": { min: 5, max: 10, step: 5, tooltip: "⚠️ Kling 2.6 only supports 5s or 10s. Any other value will be rounded automatically." }, + "Kling 3.0": { min: 3, max: 15, step: 1, tooltip: "" }, + "Kling 3.0 Motion Control": { min: 3, max: 15, step: 1, tooltip: "ℹ️ Motion Control: output duration equals the reference video's duration." }, + "Seedance 2.0": { min: 4, max: 15, step: 1, tooltip: "⚠️ Seedance 2.0 : image-to-video uniquement." }, + _veo: { min: 4, max: 8, step: 1, tooltip: "" }, +}; +function getDurationConstraint(model) { + return DURATION_CONSTRAINTS[model] ?? DURATION_CONSTRAINTS._veo; +} + +// ─── Sync video_duration selon le modèle ────────────────────────────────────── +function setupKlingDurationSync(node) { + const modelWidget = getWidget(node, "model"); + const durationWidget = getWidget(node, "video_duration"); + if (!modelWidget || !durationWidget) return; + + /** Clamp une valeur dans [min, max] en respectant step. */ + const clampDuration = (v, { min, max, step }) => { + let clamped = Math.max(min, Math.min(max, parseInt(v) || min)); + // Pour step > 1 (ex. Kling 2.6 : step=5) : snap sur le multiple le plus proche + if (step > 1) { + const steps = Math.round((clamped - min) / step); + clamped = min + steps * step; + } + return Math.max(min, Math.min(max, clamped)); + }; + + /** Recalibre min/max/step et snappe la valeur si besoin. */ + const syncDuration = () => { + if (!node._nbIsVideoMode) return; + const c = getDurationConstraint(modelWidget.value); + if (durationWidget.options) { + durationWidget.options.min = c.min; + durationWidget.options.max = c.max; + durationWidget.options.step = c.step; + } + durationWidget.tooltip = c.tooltip; + const clamped = clampDuration(durationWidget.value, c); + if (durationWidget.value !== clamped) { + durationWidget.value = clamped; + if (durationWidget.callback) durationWidget.callback(clamped); + } + node.setDirtyCanvas(true); + }; + + node._nbSyncKlingDuration = syncDuration; + syncDuration(); + + // Hooker le changement de modèle → recalibrer la durée + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncDuration(); + }; +} +// ─── Sync batch_size selon provider et mode vidéo ───────────────────────── +function setupProviderBatchSync(node) { + const providerWidget = getWidget(node, "provider"); + const batchSizeWidget = getWidget(node, "batch_size"); + if (!providerWidget || !batchSizeWidget) return; + const syncBatchState = () => { + const isVideo = node._nbIsVideoMode === true; + // VERTEX image mode : batch autorisé (multi-projets JSON) + // Seul le mode vidéo verrouille batch_size à 1 + const shouldLock = isVideo; + batchSizeWidget.disabled = shouldLock; + if (shouldLock) batchSizeWidget.value = 1; + node.setDirtyCanvas(true); + }; + // Expose pour que les fonctions activateVideoMode / activateImageMode + // puissent déclencher une resynchronisation sans passer par le callback + // du widget provider. + node._nbSyncBatchState = syncBatchState; + syncBatchState(); + const origCallback = providerWidget.callback; + providerWidget.callback = function (...args) { + if (origCallback) origCallback.apply(this, args); + syncBatchState(); + }; +} +// ─── Sync image_size (résolution) selon le modèle vidéo ───────────────────── +// Seedance 2.0 : 480p / 720p / 1080p (pas de 4K) +// Autres modèles vidéo : 720p / 1080p uniquement (pas de 480p) +function setupVideoResolutionSync(node) { + const modelWidget = getWidget(node, "model"); + const imgSizeWidget = getWidget(node, "image_size"); + if (!modelWidget || !imgSizeWidget) return; + + const syncResolution = () => { + if (!node._nbIsVideoMode) return; + const model = modelWidget.value; + const isSeedance = SEEDANCE_MODELS.includes(model); + const isKling30 = KLING30_MODELS.includes(model); + + let allowedRes, defaultRes; + if (isSeedance) { + allowedRes = ["480p", "720p", "1080p"]; + defaultRes = "720p"; + } else if (isKling30) { + allowedRes = ["720p", "1080p", "4K"]; + defaultRes = "1080p"; + } else { + allowedRes = ["720p", "1080p"]; + defaultRes = "1080p"; + } + + if (imgSizeWidget.options?.values) imgSizeWidget.options.values = [...allowedRes]; + if (!allowedRes.includes(imgSizeWidget.value)) { + imgSizeWidget.value = defaultRes; + if (imgSizeWidget.callback) imgSizeWidget.callback(defaultRes); + } + // Tooltip sur le widget modèle pour indiquer image-to-video uniquement + if (modelWidget.options) { + modelWidget.options.tooltip = isSeedance + ? "⚠️ Image-to-video uniquement" + : ""; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncVideoResolution = syncResolution; + + // Hooker le changement de modèle → recalibrer la résolution + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncResolution(); + }; +} +// ─── Sync aspect_ratio et gpt2_image_quality selon le modèle ───────────── +function setupGPT2Sync(node) { + const modelWidget = getWidget(node, "model"); + const arWidget = getWidget(node, "aspect_ratio"); + if (!modelWidget || !arWidget) return; + + /** Retourne le ratio le plus proche supporté par GPT2. */ + function nearestGPT2AR(value) { + if (GPT2_ASPECT_RATIOS.includes(value)) return value; + return GPT2_NEAREST_AR[value] || "1:1"; + } + + /** Applique ou retire le filtre GPT2 sur le dropdown aspect_ratio. */ + const syncAR = () => { + const isGPT2 = (modelWidget.value === "GPT Image 2.0"); + if (isGPT2) { + if (arWidget.options?.values) arWidget.options.values = [...GPT2_ASPECT_RATIOS]; + const snapped = nearestGPT2AR(arWidget.value); + if (arWidget.value !== snapped) { + arWidget.value = snapped; + if (arWidget.callback) arWidget.callback(snapped); + } + } else { + // Restaure la liste complète selon le mode courant + const fullList = node._nbIsVideoMode ? VIDEO_ASPECT_RATIOS : IMAGE_ASPECT_RATIOS; + if (arWidget.options?.values) arWidget.options.values = [...fullList]; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncGPT2AR = syncAR; + syncAR(); + + // Hooker le changement de modèle + const origCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origCb) origCb.apply(this, args); + syncAR(); + }; +} +// ─── Factorisation des styles des boutons ON/OFF ────────────────────────── +// Évite de dupliquer 8 lignes de style à chaque toggle (Face Swap, Breast +// Refiner, Low Neck). Chaque bouton a sa propre palette "ON". +const TOGGLE_OFF_CSS = { + text: "OFF", + background: "#3a3a3a", + color: "#888", + border: "1.5px solid #666", + boxShadow: "none", +}; +/** + * Applique l'état visuel ON/OFF à un bouton bascule. + * @param {HTMLButtonElement} btn + * @param {boolean} on + * @param {{bg:string, text?:string, border:string, glow:string}} onStyle + */ +function setToggleVisual(btn, on, onStyle) { + if (on) { + btn.textContent = onStyle.text || "ON"; + btn.style.background = onStyle.bg; + btn.style.color = "#fff"; + btn.style.border = `1.5px solid ${onStyle.border}`; + btn.style.boxShadow = `0 0 8px ${onStyle.glow}`; + } else { + btn.textContent = TOGGLE_OFF_CSS.text; + btn.style.background = TOGGLE_OFF_CSS.background; + btn.style.color = TOGGLE_OFF_CSS.color; + btn.style.border = TOGGLE_OFF_CSS.border; + btn.style.boxShadow = TOGGLE_OFF_CSS.boxShadow; + } +} +const FS_ON_STYLE = { bg: "#00c853", border: "#00e676", glow: "rgba(0,200,83,0.5)" }; +const BR_ON_STYLE = { bg: "#c2185b", border: "#f50057", glow: "rgba(245,0,87,0.4)" }; +const LN_ON_STYLE = { bg: "#6a1b9a", border: "#ab47bc", glow: "rgba(171,71,188,0.4)" }; +// CSS de base partagé par les 3 boutons ON/OFF (même taille, même rayon) +const TOGGLE_BTN_BASE_CSS = ` + padding: 4px 18px; + border-radius: 14px; + border: 1.5px solid #666; + background: #3a3a3a; + color: #888; + font-weight: 700; + font-size: 11px; + cursor: pointer; + min-width: 55px; + letter-spacing: 0.5px; + transition: all 0.2s ease; +`; +// ─── Image / Video mode toggle ──────────────────────────────────────────── +function buildModeToggle(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #1565c0; + border-radius: 9px; + padding: 8px 10px 11px 10px; + background: linear-gradient(135deg, + rgba(21,101,192,0.14) 0%, + rgba(79,195,247,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Titre ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ GENERATION MODE"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #4fc3f7; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(79,195,247,0.45); + margin-bottom: 7px; + user-select: none; + transition: color 0.25s, text-shadow 0.25s; + `; + container.appendChild(titleEl); + // ── Séparateur ──────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #1565c0 40%, #1565c0 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Boutons IMAGE / VIDÉO côte à côte ───────────────────────────────── + const btnRow = document.createElement("div"); + btnRow.style.cssText = "display:flex; gap:8px;"; + function makeChoiceBtn(label, active) { + const btn = document.createElement("button"); + btn.textContent = label; + btn.style.cssText = ` + flex: 1; + padding: 6px 4px; + border-radius: 8px; + border: 1.5px solid ${active ? "#4fc3f7" : "#444"}; + background: ${active ? "rgba(79,195,247,0.18)" : "#252525"}; + color: ${active ? "#4fc3f7" : "#555"}; + font-weight: 700; + font-size: 11px; + cursor: pointer; + letter-spacing: 1px; + box-shadow: ${active ? "0 0 7px rgba(79,195,247,0.25)" : "none"}; + transition: all 0.2s ease; + `; + return btn; + } + const imgBtn = makeChoiceBtn("🖼 IMAGES", true); + const vidBtn = makeChoiceBtn("🎬 VIDÉO", false); + btnRow.appendChild(imgBtn); + btnRow.appendChild(vidBtn); + container.appendChild(btnRow); + // ── État ────────────────────────────────────────────────────────────── + let isVideoMode = false; + const GREY_IN_VIDEO = [ + "temperature", "top_p", "negative_prompt", + "fal_safety_tolerance", "fal_enable_web_search", + "use_search", "system_instructions", "batch_size", + "gpt2_image_quality", + ]; + // ── Grise/dégrise le bloc Automation Face Swap ─────────────────────── + function setFaceSwapGreyed(greyed) { + const fsW = node.widgets?.find(w => w.name === "nb_faceswap_automation"); + const el = fsW?.element; + if (!el) return; + el.style.opacity = greyed ? "0.22" : "1"; + el.style.pointerEvents = greyed ? "none" : "auto"; + el.style.filter = greyed ? "grayscale(80%) brightness(0.35)" : "none"; + app.graph.setDirtyCanvas(true, true); + } + function updateCombo(name, newValues, newDefault) { + const w = getWidget(node, name); + if (!w) return; + if (w.options?.values) w.options.values = [...newValues]; + if (!newValues.includes(w.value)) { + w.value = newDefault; + if (w.callback) w.callback(newDefault); + } + } + // ── Visibilité des widgets vidéo-only ───────────────────────────────── + // Ces widgets sont visibles SI ET SEULEMENT SI on est en mode VIDEO. + function updateVideoOnlyWidgets(visible) { + setWidgetVisible(node, "video_duration", visible); + setWidgetVisible(node, "video_generate_audio", visible); + } + function updateVideoDurationVisibility() { updateVideoOnlyWidgets(node._nbIsVideoMode === true); } + node._nbUpdateVideoDuration = updateVideoDurationVisibility; + // ── Activer le mode IMAGE ───────────────────────────────────────────── + function activateImageMode(initial = false) { + isVideoMode = false; + node._nbIsVideoMode = false; + imgBtn.style.border = "1.5px solid #4fc3f7"; + imgBtn.style.background = "rgba(79,195,247,0.18)"; + imgBtn.style.color = "#4fc3f7"; + imgBtn.style.boxShadow = "0 0 7px rgba(79,195,247,0.25)"; + vidBtn.style.border = "1.5px solid #444"; + vidBtn.style.background = "#252525"; + vidBtn.style.color = "#555"; + vidBtn.style.boxShadow = "none"; + container.style.border = "2px solid #1565c0"; + container.style.background = "linear-gradient(135deg, rgba(21,101,192,0.14) 0%, rgba(79,195,247,0.06) 100%)"; + titleEl.style.color = "#4fc3f7"; + titleEl.style.textShadow = "0 0 10px rgba(79,195,247,0.45)"; + // IMAGE_MODELS_DEFAULT = source de vérité (Python déclare image+vidéo + // pour la validation serveur, donc options.values n'est plus fiable) + const modelW = getWidget(node, "model"); + if (modelW) { + const vals = IMAGE_MODELS_DEFAULT; + if (modelW.options?.values) modelW.options.values = [...vals]; + if (!vals.includes(modelW.value)) { + modelW.value = vals[0]; + if (modelW.callback) modelW.callback(vals[0]); + } + if (modelW._imgOrigTooltip !== undefined) { + if (modelW.options) modelW.options.tooltip = modelW._imgOrigTooltip; + delete modelW._imgOrigTooltip; + } + } + updateCombo("aspect_ratio", IMAGE_ASPECT_RATIOS, "1:1"); + updateCombo("image_size", IMAGE_RESOLUTIONS, "2K"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "image_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, false); + // Re-synchronise batch_size et aspect_ratio (Kling) en mode image + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(false), 60); + if (!initial) { + syncNodeWidget(node, "video_mode_enabled", false); + app.graph.setDirtyCanvas(true, true); + } + } + // ── Activer le mode VIDÉO ───────────────────────────────────────────── + function activateVideoMode() { + isVideoMode = true; + node._nbIsVideoMode = true; + vidBtn.style.border = "1.5px solid #ce93d8"; + vidBtn.style.background = "rgba(206,147,216,0.18)"; + vidBtn.style.color = "#ce93d8"; + vidBtn.style.boxShadow = "0 0 7px rgba(206,147,216,0.3)"; + imgBtn.style.border = "1.5px solid #444"; + imgBtn.style.background = "#252525"; + imgBtn.style.color = "#555"; + imgBtn.style.boxShadow = "none"; + container.style.border = "2px solid #6a1b9a"; + container.style.background = "linear-gradient(135deg, rgba(106,27,154,0.14) 0%, rgba(206,147,216,0.06) 100%)"; + titleEl.style.color = "#ce93d8"; + titleEl.style.textShadow = "0 0 10px rgba(206,147,216,0.45)"; + // VIDEO_MODELS = source de vérité — pas de sauvegarde _imgOrigValues + // car options.values contient maintenant image+vidéo côté Python + const modelW = getWidget(node, "model"); + if (modelW) { + if (modelW.options?.values) modelW.options.values = [...VIDEO_MODELS]; + if (!VIDEO_MODELS.includes(modelW.value)) { + modelW.value = VIDEO_MODELS[0]; + if (modelW.callback) modelW.callback(VIDEO_MODELS[0]); + } + if (modelW.options?.tooltip) { + modelW._imgOrigTooltip = modelW.options.tooltip; + modelW.options.tooltip = ""; + } + } + updateCombo("aspect_ratio", VIDEO_ASPECT_RATIOS, "16:9"); + updateCombo("image_size", VIDEO_RESOLUTIONS, "1080p"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "video_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, true); + // Force batch_size = 1, synchronise aspect_ratio, durée et résolution selon le modèle + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + node._nbSyncKlingDuration?.(); + node._nbSyncVideoResolution?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(true), 60); + syncNodeWidget(node, "video_mode_enabled", true); + app.graph.setDirtyCanvas(true, true); + } + // ── Listeners ───────────────────────────────────────────────────────── + imgBtn.addEventListener("click", () => { if (isVideoMode) activateImageMode(); }); + vidBtn.addEventListener("click", () => { if (!isVideoMode) activateVideoMode(); }); + node._modeToggleAPI = { activateImageMode, activateVideoMode }; + // ── État initial SYNCHRONE (mode image par défaut) ──────────────────── + // Masquer video_duration AVANT d'ajouter le DOM widget évite un + // redimensionnement visible du node ~250 ms après le démarrage. + node._nbIsVideoMode = false; + updateVideoOnlyWidgets(false); + // ── Ajout DOM widget ────────────────────────────────────────────────── + const domWidget = node.addDOMWidget( + "nb_mode_toggle", "mode_toggle_div", container, + { serialize: false, hideOnZoom: false } + ); + if (domWidget) domWidget.computeSize = (w) => [w, 95]; + // ── Placer en PREMIER ───────────────────────────────────────────────── + if (domWidget) { + const idx = node.widgets.indexOf(domWidget); + if (idx > 0) { node.widgets.splice(idx, 1); node.widgets.unshift(domWidget); } + app.graph.setDirtyCanvas(true, true); + } + // ── Filtrage initial du dropdown "model" (mode image par défaut) ───── + // On ne fait QUE filtrer la liste — pas d'appel à activateImageMode() + // pour éviter de déclencher des callbacks qui perturbent la visibilité + // des widgets DOM (inputEl créés après le premier rendu). + setTimeout(() => { + const modelW = getWidget(node, "model"); + if (!modelW || node._nbIsVideoMode) return; + if (modelW.options?.values) modelW.options.values = [...IMAGE_MODELS_DEFAULT]; + if (!IMAGE_MODELS_DEFAULT.includes(modelW.value)) modelW.value = IMAGE_MODELS_DEFAULT[0]; + }, 200); + // ── Sync UI ↔ widget "video_mode_enabled" après chargement workflow ── + // Au chargement d'un workflow, ComfyUI restaure la valeur du widget + // caché `video_mode_enabled`, mais la variable locale isVideoMode reste + // à false. Résultat : l'UI montre IMAGES mais le backend reçoit + // video_mode_enabled=true → "Modèle vidéo inconnu : Nano Banana Pro". + // On fixe ça en synchronisant l'UI avec la valeur réelle du widget ~350ms + // après le onNodeCreated (délai suffisant pour que configure() ait injecté + // les valeurs sauvegardées). + setTimeout(() => { + const videoModeWidget = getWidget(node, "video_mode_enabled"); + const savedIsVideo = videoModeWidget?.value === true; + if (savedIsVideo && !node._nbIsVideoMode) { + // Workflow sauvegardé en mode vidéo → bascule l'UI en vidéo + activateVideoMode(); + } else { + // Force explicitement le widget à false pour éviter qu'une + // valeur "truthy" résiduelle (1, "true"…) passe côté Python + syncNodeWidget(node, "video_mode_enabled", false); + } + }, 350); +} +// ─── Automation Face Swap UI ────────────────────────────────────────────── +function buildFaceSwapUI(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #e65c00; + border-radius: 9px; + padding: 9px 10px 16px 10px; + background: linear-gradient(135deg, + rgba(230,92,0,0.13) 0%, + rgba(255,140,0,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Title ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ AUTOMATION FACE SWAP"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #ff8c00; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(255,140,0,0.45); + margin-bottom: 7px; + transition: color 0.25s, text-shadow 0.25s; + user-select: none; + `; + container.appendChild(titleEl); + // ── Separator ───────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #e65c00 40%, #e65c00 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Info hint ───────────────────────────────────────────────────────── + const hintEl = document.createElement("div"); + hintEl.textContent = "ℹ️ Image 1 = reference face · Image 2 = face to swap"; + hintEl.style.cssText = ` + font-size: 10px; + color: #999; + font-style: italic; + text-align: center; + margin-bottom: 8px; + user-select: none; + `; + container.appendChild(hintEl); + // ── Helper pour construire une ligne "label + bouton ON/OFF" ────────── + function makeToggleRow(labelText, tooltip, hidden = false) { + const row = document.createElement("div"); + row.style.cssText = ` + display: ${hidden ? "none" : "flex"}; + align-items: center; + gap: 8px; + ${hidden ? "margin-top: 8px; padding-top: 7px; border-top: 1px solid rgba(230,92,0,0.3);" : ""} + `; + const label = document.createElement("span"); + label.textContent = labelText; + label.title = tooltip; + label.style.cssText = ` + font-size: 12px; + color: #ccc; + flex: 1; + user-select: none; + `; + const btn = document.createElement("button"); + btn.textContent = "OFF"; + btn.title = tooltip; + btn.style.cssText = TOGGLE_BTN_BASE_CSS; + row.appendChild(label); + row.appendChild(btn); + return { row, btn }; + } + // ── Face Swap toggle ────────────────────────────────────────────────── + const { row: toggleRow, btn: toggleBtn } = makeToggleRow( + "Face Swap", + "Activate to run Automation Face Swap.\nImage 1 = reference face · Image 2 = face to swap", + false + ); + container.appendChild(toggleRow); + // ── Breast Refiner row (hidden until automation ON) ────────────────── + const { row: brRow, btn: brBtn } = makeToggleRow( + "Breast Refiner", + "This tool enhances breast shape by defining the upper curve for a more natural look. May trigger NSFW restrictions.", + true + ); + container.appendChild(brRow); + // ── Low Neck row (hidden until automation ON) ──────────────────────── + const { row: lnRow, btn: lnBtn } = makeToggleRow( + "Low Neck", + "Add a low neck, might be flagged as sensitive content.", + true + ); + container.appendChild(lnRow); + // ── Facial Expression section (hidden until automation ON) ─────────── + const EXPRESSIONS = [ + "Neutral", "Sensual", "Playful", "Subtle smile", "Smile", "Laugh", + ]; + const exprSection = document.createElement("div"); + exprSection.style.cssText = ` + display: none; + flex-direction: column; + gap: 6px; + margin-top: 8px; + padding-top: 7px; + border-top: 1px solid rgba(230,92,0,0.3); + `; + const exprTitleEl = document.createElement("div"); + exprTitleEl.textContent = "Facial Expression"; + exprTitleEl.style.cssText = ` + font-size: 11px; + font-weight: 600; + color: #aaa; + letter-spacing: 0.8px; + user-select: none; + `; + exprSection.appendChild(exprTitleEl); + const exprGrid = document.createElement("div"); + exprGrid.style.cssText = ` + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 4px; + `; + const exprBtns = {}; + function selectExpression(value) { + for (const [v, btn] of Object.entries(exprBtns)) { + const active = (v === value); + btn.style.background = active ? "rgba(255,140,0,0.35)" : "#2a2a2a"; + btn.style.color = active ? "#ff8c00" : "#888"; + btn.style.border = active ? "1.5px solid #e65c00" : "1.5px solid #444"; + btn.style.fontWeight = active ? "700" : "400"; + } + syncNodeWidget(node, "face_expression", value); + } + for (const value of EXPRESSIONS) { + const btn = document.createElement("button"); + btn.textContent = value; + btn.style.cssText = ` + padding: 4px 6px; + border-radius: 10px; + border: 1.5px solid #444; + background: #2a2a2a; + color: #888; + font-size: 10.5px; + cursor: pointer; + transition: all 0.15s ease; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; + btn.addEventListener("click", () => selectExpression(value)); + exprBtns[value] = btn; + exprGrid.appendChild(btn); + } + exprSection.appendChild(exprGrid); + container.appendChild(exprSection); + selectExpression("Neutral"); + // ── State ───────────────────────────────────────────────────────────── + let automationActive = false; + let breastRefinerActive = false; + let lowNeckActive = false; + const FS_HEIGHT_OFF = 115; + const FS_HEIGHT_ON = 300; + let _blockH = FS_HEIGHT_OFF; + // ── Face Swap toggle ────────────────────────────────────────────────── + toggleBtn.addEventListener("click", () => { + automationActive = !automationActive; + _blockH = automationActive ? FS_HEIGHT_ON : FS_HEIGHT_OFF; + setToggleVisual(toggleBtn, automationActive, FS_ON_STYLE); + if (automationActive) { + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + } else { + container.style.border = "2px solid #e65c00"; + container.style.background = "linear-gradient(135deg, rgba(230,92,0,0.13) 0%, rgba(255,140,0,0.06) 100%)"; + titleEl.style.color = "#ff8c00"; + titleEl.style.textShadow = "0 0 10px rgba(255,140,0,0.45)"; + brRow.style.display = "none"; + lnRow.style.display = "none"; + exprSection.style.display = "none"; + // Reset sub-toggles when automation is switched off + if (breastRefinerActive) { + breastRefinerActive = false; + setToggleVisual(brBtn, false, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", false); + } + if (lowNeckActive) { + lowNeckActive = false; + setToggleVisual(lnBtn, false, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", false); + } + } + applyAutomationState(node, automationActive); + syncNodeWidget(node, "face_swap_enabled", automationActive); + // Force la taille immédiatement (pas de latence au premier clic) + const newSize = node.computeSize(); + node.size[0] = Math.max(node.size[0], newSize[0]); + node.size[1] = newSize[1]; + app.graph.setDirtyCanvas(true, true); + }); + // ── Breast Refiner toggle ───────────────────────────────────────────── + brBtn.addEventListener("click", () => { + breastRefinerActive = !breastRefinerActive; + setToggleVisual(brBtn, breastRefinerActive, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", breastRefinerActive); + app.graph.setDirtyCanvas(true); + }); + // ── Low Neck toggle ─────────────────────────────────────────────────── + lnBtn.addEventListener("click", () => { + lowNeckActive = !lowNeckActive; + setToggleVisual(lnBtn, lowNeckActive, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", lowNeckActive); + app.graph.setDirtyCanvas(true); + }); + // ── Add DOM widget to node ──────────────────────────────────────────── + const domWidget = node.addDOMWidget("nb_faceswap_automation", "automation_div", container, { + serialize: false, + hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + // ── Restaure l'état sauvegardé dans le workflow ─────────────────────── + // Le DOM démarre à OFF par défaut ; on le réaligne sur les widgets Python + // pour que l'état visuel corresponde toujours à ce qui sera exécuté. + const _savedFS = getWidget(node, "face_swap_enabled")?.value === true; + if (_savedFS) { + automationActive = true; + _blockH = FS_HEIGHT_ON; + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + setToggleVisual(toggleBtn, true, FS_ON_STYLE); + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + applyAutomationState(node, true); + } + // Breast Refiner et Low Neck : toujours OFF au démarrage. + // On réinitialise le widget Python même si le workflow les avait sauvegardés + // à true, pour éviter qu'ils se réactivent silencieusement entre sessions. + syncNodeWidget(node, "breast_refiner_enabled", false); + syncNodeWidget(node, "low_neck_enabled", false); + // breastRefinerActive et lowNeckActive restent false, boutons restent OFF. + // Masque les widgets Python cachés (IMMÉDIATEMENT, pas en setTimeout, pour + // éviter que le node soit dessiné grand puis rétréci juste après). + const HIDDEN_PY_WIDGETS = [ + "face_swap_enabled", "breast_refiner_enabled", "low_neck_enabled", + "face_expression", "video_mode_enabled", + ]; + for (const name of HIDDEN_PY_WIDGETS) { + const w = getWidget(node, name); + if (!w) continue; + w._fsOrigComputeSize = w.computeSize; + w.computeSize = () => [0, -4]; + w.hidden = true; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + } + app.graph.setDirtyCanvas(true, true); +} +// ─── Preset panel (10 slots, mode-aware, avec champ nom) ────────────────── +function buildPresetUI(node) { + const NUM_PRESETS = 10; + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #37474f; + border-radius: 9px; + padding: 8px 10px 10px 10px; + background: linear-gradient(135deg, + rgba(55,71,79,0.14) 0%, + rgba(96,125,139,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + `; + forwardWheelToCanvas(container); + const titleEl = document.createElement("div"); + titleEl.textContent = "💾 PRESETS"; + titleEl.style.cssText = ` + font-weight: 700; font-size: 11.5px; color: #90a4ae; + letter-spacing: 2px; text-align: center; + margin-bottom: 7px; user-select: none; + `; + container.appendChild(titleEl); + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #37474f 40%, #37474f 60%, transparent); + opacity: 0.55; margin-bottom: 7px; + `; + container.appendChild(sep); + const list = document.createElement("div"); + list.style.cssText = "display: flex; flex-direction: column; gap: 4px;"; + container.appendChild(list); + const slotRows = {}; + const slotInputs = {}; + function markSlotFilled(n, filled, name) { + const row = slotRows[n]; + const input = slotInputs[n]; + if (!row) return; + row.style.border = filled ? "1px solid rgba(79,195,247,0.3)" : "1px solid #2a2a2a"; + row.style.background = filled ? "rgba(79,195,247,0.04)" : "#1a1a1a"; + if (input && name !== undefined) input.value = name || ""; + } + function buildSlot(n) { + const row = document.createElement("div"); + row.style.cssText = ` + display: flex; align-items: center; gap: 4px; + padding: 3px 5px; border-radius: 6px; + border: 1px solid #2a2a2a; background: #1a1a1a; + transition: border 0.2s, background 0.2s; + `; + slotRows[n] = row; + const label = document.createElement("span"); + label.textContent = `${n < 10 ? " " : ""}${n}`; + label.style.cssText = ` + font-size: 9.5px; color: #555; min-width: 14px; + user-select: none; font-weight: 700; font-variant-numeric: tabular-nums; + `; + const nameInput = document.createElement("input"); + nameInput.type = "text"; + nameInput.placeholder = `preset ${n}`; + nameInput.style.cssText = ` + flex: 1; min-width: 0; + background: #111; border: 1px solid #333; border-radius: 4px; + color: #aaa; font-size: 9.5px; padding: 2px 5px; + outline: none; font-family: 'Segoe UI', Arial, sans-serif; + `; + nameInput.addEventListener("focus", () => nameInput.style.borderColor = "#546e7a"); + nameInput.addEventListener("blur", () => nameInput.style.borderColor = "#333"); + nameInput.addEventListener("keydown", e => e.stopPropagation()); + slotInputs[n] = nameInput; + const btnBase = ` + padding: 2px 8px; border-radius: 4px; font-size: 9px; + font-weight: 700; cursor: pointer; white-space: nowrap; + transition: all 0.15s ease; letter-spacing: 0.4px; + `; + const saveBtn = document.createElement("button"); + saveBtn.textContent = "SAVE"; + saveBtn.title = `Sauvegarder dans le slot ${n}`; + saveBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + const loadBtn = document.createElement("button"); + loadBtn.textContent = "LOAD"; + loadBtn.title = `Charger le slot ${n}`; + loadBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + row.appendChild(label); + row.appendChild(nameInput); + row.appendChild(saveBtn); + row.appendChild(loadBtn); + list.appendChild(row); + saveBtn.addEventListener("click", async () => { + const params = { preset_name: nameInput.value.trim() }; + for (const w of node.widgets || []) { + if (w.name && w.value !== undefined + && w.type !== "button" && w.type !== "dom_widget" + && !w.name.startsWith("nb_")) { + params[w.name] = w.value; + } + } + try { + const res = await fetch("/nb_aio/save_preset", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ slot: n, params }), + }); + const data = await res.json(); + if (data.success) { + markSlotFilled(n, true, params.preset_name); + saveBtn.style.cssText = btnBase + "border:1px solid #00c853; background:#1b5e20; color:#69f0ae;"; + setTimeout(() => { + saveBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + } + } catch (e) { console.error("[NB Presets] Save error:", e); } + }); + loadBtn.addEventListener("click", async () => { + try { + const res = await fetch("/nb_aio/load_presets"); + const data = await res.json(); + if (!data.success) return; + const preset = data.presets?.[String(n)]; + if (!preset) return; + const isVideo = preset.video_mode_enabled === true; + if (isVideo && !node._nbIsVideoMode) { + node._modeToggleAPI?.activateVideoMode(); + } else if (!isVideo && node._nbIsVideoMode) { + node._modeToggleAPI?.activateImageMode(); + } + if (preset.preset_name !== undefined) { + nameInput.value = preset.preset_name || ""; + } + markSlotFilled(n, true, preset.preset_name); + const SKIP = new Set(["video_mode_enabled", "preset_name"]); + for (const [key, value] of Object.entries(preset)) { + if (SKIP.has(key)) continue; + syncNodeWidget(node, key, value); + } + loadBtn.style.cssText = btnBase + "border:1px solid #2962ff; background:#0d47a1; color:#82b1ff;"; + setTimeout(() => { + loadBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + app.graph.setDirtyCanvas(true, true); + } catch (e) { console.error("[NB Presets] Load error:", e); } + }); + } + for (let i = 1; i <= NUM_PRESETS; i++) buildSlot(i); + const PANEL_H = 368; + const domWidget = node.addDOMWidget("nb_presets_ui", "presets_div", container, { + serialize: false, hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, PANEL_H]; + fetch("/nb_aio/load_presets") + .then(r => r.json()) + .then(data => { + if (!data.success) return; + for (let i = 1; i <= NUM_PRESETS; i++) { + const p = data.presets?.[String(i)]; + if (p) markSlotFilled(i, true, p.preset_name); + } + }) + .catch(() => {}); +} +// ─── Prompt widget colour coding ────────────────────────────────────────── +function stylePromptWidgets(node) { + setTimeout(() => { + const pos = getWidget(node, "prompt"); + if (pos?.inputEl) { + pos.inputEl.style.borderLeft = "3px solid #00c853"; + pos.inputEl.style.paddingLeft = "6px"; + pos.inputEl.style.borderRadius = "3px"; + } + const neg = getWidget(node, "negative_prompt"); + if (neg?.inputEl) { + neg.inputEl.style.borderLeft = "3px solid #e53935"; + neg.inputEl.style.paddingLeft = "6px"; + neg.inputEl.style.borderRadius = "3px"; + } + }, 200); +} +// ─── Extension registration ─────────────────────────────────────────────── +app.registerExtension({ + name: "NanoBananaAIO.FaceSwap", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "NanoBananaAIO") return; + const onCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onCreated?.apply(this, arguments); + const node = this; + stylePromptWidgets(node); + // Mode toggle en premier (synchrone) — place le widget tout en haut + buildModeToggle(node); + setTimeout(() => setupKlingAspectRatioSync(node), 500); + setTimeout(() => setupKlingDurationSync(node), 500); + setTimeout(() => setupProviderBatchSync(node), 500); + setTimeout(() => setupGPT2Sync(node), 500); + setTimeout(() => setupVideoResolutionSync(node), 500); + setTimeout(() => buildFaceSwapUI(node), 400); + setTimeout(() => buildPresetUI(node), 450); + // Nettoyage tardif des widgets preset hérités (autre JS) + setTimeout(() => { + if (!node.widgets) return; + const KEEP = new Set([ + "nb_faceswap_automation", "nb_presets_ui", "nb_mode_toggle", + "face_expression", "face_swap_enabled", "breast_refiner_enabled", + "low_neck_enabled", "video_mode_enabled", + ]); + const isLegacy = (w) => { + if (!w.name) return false; + if (KEEP.has(w.name)) return false; + if (w.name.startsWith("nb_")) return false; + const n = w.name.toLowerCase(); + return ( + w.type === "button" || + n.includes("preset") || + n.includes("slot") + ); + }; + for (let i = node.widgets.length - 1; i >= 0; i--) { + const w = node.widgets[i]; + if (!isLegacy(w)) continue; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + node.widgets.splice(i, 1); + } + // Force-hide des widgets Python automation (canvas widgets LiteGraph) + for (const name of ["face_expression", "face_swap_enabled", + "breast_refiner_enabled", "low_neck_enabled", + "video_mode_enabled"]) { + const w = getWidget(node, name); + if (!w) continue; + w.hidden = true; + w.computeSize = () => [0, -4]; + if (w.inputEl) { try { w.inputEl.remove(); } catch (_) {} w.inputEl = null; } + if (w.element) { try { w.element.remove(); } catch (_) {} w.element = null; } + } + app.graph.setDirtyCanvas(true, true); + }, 1200); + // ── Restauration de la taille sauvegardée (workflow.json) ─────────── + // Les setTimeouts ci-dessus ajoutent des DOM widgets et appellent + // setDirtyCanvas, ce qui peut écraser la taille restaurée par + // configure(). On ré-applique la taille sauvegardée après le dernier + // setTimeout (1200ms) avec une petite marge. + setTimeout(() => { + if (node._nbSavedSize && Array.isArray(node._nbSavedSize)) { + node.size[0] = node._nbSavedSize[0]; + node.size[1] = node._nbSavedSize[1]; + app.graph.setDirtyCanvas(true, true); + } else { + // Nouveau node (jamais sauvegardé) — applique une taille + // par défaut généreuse pour que les prompt boxes soient + // utilisables sans avoir à redimensionner manuellement. + const DEFAULT_W = 520; + const DEFAULT_H = 900; + if (node.size[0] < DEFAULT_W) node.size[0] = DEFAULT_W; + if (node.size[1] < DEFAULT_H) node.size[1] = DEFAULT_H; + app.graph.setDirtyCanvas(true, true); + } + }, 1300); + }; + // ── Hook onConfigure : capture la taille sauvée dans le workflow ───── + // configure(info) est appelé par LiteGraph lors de la restauration d'un + // workflow. info.size contient la taille que l'utilisateur avait à la + // session précédente. On la stocke pour la ré-appliquer après que les + // DOM widgets aient fini leur setup. + const onConfigure = nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure = function (info) { + const r = onConfigure?.apply(this, arguments); + try { + if (info && Array.isArray(info.size) && info.size.length >= 2) { + this._nbSavedSize = [info.size[0], info.size[1]]; + } + } catch (_) { /* noop */ } + return r; + }; + }, +}); \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260505_163338_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260505_163338_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1c3f2ca7485f4f8512d8714ef4a21da107d633 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260505_163338_nano_banana_aio.py @@ -0,0 +1,6771 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Shared session for all KIE requests — reuses TCP connection + looks like a browser +_kie_session = requests.Session() +_kie_session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) +}) + +# KIE session with automatic retry on connection errors (RemoteDisconnected, etc.) +def _make_kie_session() -> "requests.Session": + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + session = requests.Session() + retry = Retry( + total=4, # up to 4 total attempts + connect=4, # retry on connection errors (RemoteDisconnected) + read=2, # retry on read errors + backoff_factor=1.5, # 1.5s, 2.25s, 3.4s between retries + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["POST", "GET"], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("https://", adapter) + session.mount("http://", adapter) + session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) + }) + return session + +_kie_session = _make_kie_session() + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K · video: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "auto", + "tooltip": "auto = détecte l'aspect ratio des images en input " + "et sélectionne le plus proche parmi les ratios supportés. " + "Fallback 1:1 si aucune image en input."}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = False + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── AUTO ASPECT RATIO ───────────────────────────────────────── + if aspect_ratio == "auto": + _AR_SUPPORTED = [ + ("1:1", 1/1), ("2:3", 2/3), ("3:2", 3/2), + ("3:4", 3/4), ("4:3", 4/3), ("4:5", 4/5), + ("5:4", 5/4), ("9:16", 9/16), ("16:9", 16/9), + ("21:9", 21/9), + ] + if input_images: + _ratios = [] + for _t in input_images: + # tensor shape: [B, H, W, C] or [H, W, C] + _sh = _t.shape + _h, _w = (_sh[-3], _sh[-2]) if len(_sh) == 4 else (_sh[0], _sh[1]) + if _h > 0 and _w > 0: + _ratios.append(_w / _h) + if _ratios: + _avg = sum(_ratios) / len(_ratios) + aspect_ratio = min(_AR_SUPPORTED, key=lambda x: abs(x[1] - _avg))[0] + print(f"🔲 [Auto AR] avg ratio={_avg:.3f} → {aspect_ratio}") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] could not read image dims → fallback 1:1") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] no input images → fallback 1:1") + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + + + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 300 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + # ── Diagnostic Vertex (lecture prompt_feedback / usage_metadata) ── + # But : transformer les "no image data" silencieux en messages + # explicites avec la raison du blocage cote serveur. + _pf_bits = [] + _meta_bits = [] + if _response and not isinstance(_response, Exception): + try: + _pf = getattr(_response, "prompt_feedback", None) \ + or getattr(_response, "promptFeedback", None) + if _pf: + _br = getattr(_pf, "block_reason", None) \ + or getattr(_pf, "blockReason", None) + _brm = getattr(_pf, "block_reason_message", None) \ + or getattr(_pf, "blockReasonMessage", None) + _sr = getattr(_pf, "safety_ratings", None) \ + or getattr(_pf, "safetyRatings", None) or [] + if _br: + _pf_bits.append(f"block_reason={_br}") + if _brm: + _pf_bits.append(f"block_message={_brm!r}") + _blocked_cats = [] + for _r in _sr: + _blk = getattr(_r, "blocked", False) + _cat = getattr(_r, "category", None) + _prb = getattr(_r, "probability", None) + if _blk: + _blocked_cats.append(f"{_cat}:{_prb}") + if _blocked_cats: + _pf_bits.append(f"blocked_categories=[{', '.join(map(str, _blocked_cats))}]") + except Exception as _e_pf: + _pf_bits.append(f"pf_parse_err={_e_pf}") + try: + _um = getattr(_response, "usage_metadata", None) \ + or getattr(_response, "usageMetadata", None) + if _um: + _ptc = getattr(_um, "prompt_token_count", None) \ + or getattr(_um, "promptTokenCount", None) + _ctc = getattr(_um, "candidates_token_count", None) \ + or getattr(_um, "candidatesTokenCount", None) + _meta_bits.append(f"tokens=in:{_ptc}/out:{_ctc}") + except Exception: + pass + try: + _cands_count = len(getattr(_response, "candidates", None) or []) + _meta_bits.append(f"candidates_count={_cands_count}") + except Exception: + pass + + # ── Diagnostic erreur SDK (headers HTTP, request_id, body) ──────── + _err_bits = [] + if _gen_error is not None: + try: + _resp = getattr(_gen_error, "response", None) + if _resp is not None: + _hdrs = dict(getattr(_resp, "headers", {}) or {}) + for _k in ("x-request-id", "X-Request-Id", "x-goog-request-id", + "x-ratelimit-remaining", "x-ratelimit-reset"): + _v = _hdrs.get(_k) + if _v: + _err_bits.append(f"{_k}={_v}") + _body = getattr(_resp, "text", None) + if _body and isinstance(_body, str): + _bsnip = _body[:300] + _err_bits.append(f"body_snippet={_bsnip!r}") + _code = getattr(_gen_error, "code", None) \ + or getattr(_gen_error, "status_code", None) + if _code: + _err_bits.append(f"http_code={_code}") + except Exception: + pass + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + # Logs diagnostic — toujours imprimer ce qu'on a, meme si vide + if _pf_bits: + print(f"\U0001f50d {tag} prompt_feedback: {' | '.join(_pf_bits)}") + if _meta_bits: + print(f"\U0001f50d {tag} response_meta: {' | '.join(_meta_bits)}") + if _err_bits: + print(f"\U0001f50d {tag} sdk_error_detail: {' | '.join(_err_bits)}") + # Concatenation dans le message d erreur final (visible dans les logs batch) + _diag_suffix = "" + if _pf_bits: + _diag_suffix += " | " + ", ".join(_pf_bits) + if _err_bits and not _gen_error: + _diag_suffix += " | " + ", ".join(_err_bits) + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}{_diag_suffix}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0, "includeThoughts": False}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.30) + pad_h = int(fh * 0.30) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + try: + resp = _kie_session.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + try: + resp = _kie_session.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _kie_session.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "UGljdHVyZSAxIGRlZmluZXMgdGhlIGlkZW50aXR5LCBmYWNpYWwgYW5hdG9teSBhbmQgaGFpciBjaGFyYWN0ZXJpc3RpY3Mgb2YgdGhlIHN1YmplY3QuCk1haW50YWluIHRoZSBwb3NlLCBmcmFtaW5nLCBjbG90aGluZyBhbmQgZW52aXJvbm1lbnQgZnJvbSBwaWN0dXJlIDIuCkdlbmVyYXRlIGEgbmV3bHkgcmVjb25zdHJ1Y3RlZCB2ZXJzaW9uIG9mIHRoZSBzdWJqZWN0IGZyb20gcGljdHVyZSAxIG5hdHVyYWxseSBwaG90b2dyYXBoZWQgaW4gdGhlIHNjZW5lLCBwb3NlIGFuZCBjYW1lcmEgZnJhbWluZyBvZiBwaWN0dXJlIDIuClVzZSBwaWN0dXJlIDEgYXMgYSB2aXN1YWwgZ3VpZGUgdG8gdW5kZXJzdGFuZCB0aGUgZmFjZSBzdHJ1Y3R1cmUsIApoYWlyIGNvbG9yIGFuZCBoYWlyIGxlbmd0aCDigJQgdGhlbiBmcmVlbHkgcmVnZW5lcmF0ZSBldmVyeXRoaW5nIGZyb20gc2NyYXRjaC4KVGhlIHN1YmplY3QgbXVzdCBsb29rIGxpa2UgYSBzaW5nbGUgbmF0dXJhbGx5IHBob3RvZ3JhcGhlZCBwZXJzb24gY2FwdHVyZWQgaW4tY2FtZXJhLgpUaGUgbGlnaHRpbmcgb24gdGhlIGZhY2UgYW5kIGhhaXIgbXVzdCBwZXJmZWN0bHkgbWF0Y2ggdGhlIG92ZXJhbGwgbGlnaHRpbmcgb2YgcGljdHVyZSAyLgpQcmVzZXJ2ZSB0aGUgaWRlbnRpdHkgY29uc2lzdGVuY3kgYW5kIGZhY2lhbCBwcm9wb3J0aW9ucyBkZWZpbmVkIGJ5IHBpY3R1cmUgMS4KR2VuZXJhdGUgYSBORVcgZmFjaWFsIGV4cHJlc3Npb24gbmF0dXJhbGx5IHN1aXRlZCB0byB0aGUgYm9keSBwb3NlLCBuZXZlciBjb3B5IHRoZSBleHByZXNzaW9uIGZyb20gcGljdHVyZSAxLgpObyBmbG9hdGluZyBmYWNlIGVmZmVjdCBvciBpbmNvcnJlY3QgaGVhZCBwbGFjZW1lbnQKRmFjZSBtdXN0IGluaGVyaXQgdGhlIHNhbWUgbmF0dXJhbCBSQVcgcGhvdG8gbG9vayBhcyB0aGUgYm9keQoKQ1JJU1BZIFJBVyBQSE9UTyBxdWFsaXR5LgpIZWFkLCBuZWNrIGFuZCBib2R5IG11c3Qgc2hhcmUgaWRlbnRpY2FsIHBlcnNwZWN0aXZlLCBsaWdodGluZyBhbmQgcGhvdG9ncmFwaGljIGNoYXJhY3RlcmlzdGljcywgd2l0aCBjbGVhbiBlZGdlIGJsZW5kaW5nLgoKUEVSRkVDVCBTS0lOIE1BVENISU5HIOKAlCBDUklUSUNBTDoKCi0gRmFjZSBza2luIG11c3QgcGVyZmVjdGx5IGluaGVyaXQgdGhlIGJvZHkgc2tpbiB0b25lLCB1bmRlcnRvbmUsIHRleHR1cmUsIHBvcmVzLCBzaGFycG5lc3MgYW5kIGR5bmFtaWMgcmFuZ2UKLSBJZGVudGljYWwgbGlnaHRpbmcgcmVzcG9uc2UgYXMgYm9keTogc2FtZSBzaGFkb3dzLCBoaWdobGlnaHRzLCBleHBvc3VyZSwgd2hpdGUgYmFsYW5jZSBhbmQgY29sb3IgdGVtcGVyYXR1cmUKLSBDb21wbGV0ZWx5IHNlYW1sZXNzIGphd2xpbmUgYW5kIG5lY2sgdHJhbnNpdGlvbgotIE5vIHNlYW0sIG5vIGhhbG8sIG5vIGNvbG9yIHNoaWZ0LCBubyBicmlnaHRuZXNzIG1pc21hdGNoLCBubyB0ZXh0dXJlIGRpZmZlcmVuY2UKLSBDb25zaXN0ZW50IHBob3RvZ3JhcGhpYyBjb2hlcmVuY2UgYWNyb3NzIHRoZSBlbnRpcmUgc3ViamVjdC4KLSBGYWNlIG11c3QgbG9vayBuYXR1cmFsbHkgYXR0YWNoZWQgdG8gdGhlIGJvZHkgaW4gb25lIHNpbmdsZSB1bnRvdWNoZWQgUkFXIHBob3RvCgoKUEVSRkVDVCBIRUFEIFNDQUxFIOKAlCBDUklUSUNBTDoKCi0gSGVhZCBzaXplIG11c3QgcmVtYWluIGFuYXRvbWljYWxseSBwcm9wb3J0aW9uYWwgdG8gdGhlIGJvZHkgYW5kIGNhbWVyYSBwZXJzcGVjdGl2ZQotIEhlYWQgbXVzdCBORVZFUiBhcHBlYXIgb3ZlcnNpemVkIHJlbGF0aXZlIHRvIHNob3VsZGVycywgbmVjayBvciB0b3JzbwotIEZhY2Ugd2lkdGggbXVzdCBzdGF5IG5hdHVyYWxseSBhbGlnbmVkIHdpdGggbmVjayB3aWR0aAotIE1haW50YWluIHJlYWxpc3RpYyBkaXN0YW5jZSBiZXR3ZWVuIGNoaW4sIHNob3VsZGVycyBhbmQgdXBwZXIgdG9yc28KLSBJZiB1bmNlcnRhaW4sIEFMV0FZUyBwcmVmZXIgYSBzbGlnaHRseSBzbWFsbGVyIGhlYWQgc2l6ZQotIEF2b2lkIGVubGFyZ2VkIGZhY2lhbCBwcm9wb3J0aW9ucywgem9vbWVkLWluIGZhY2UgcmVuZGVyaW5nIG9yIGV4YWdnZXJhdGVkIGhlYWQgc2NhbGUKCgpIQUlSIOKAlCBDUklUSUNBTDoKLSBIYWlyIGNvbG9yIGFuZCBsZW5ndGggZnJvbSBwaWN0dXJlIDEgYXMgaW5zcGlyYXRpb24gb25seQotIE5FVkVSIHJlcHJvZHVjZSB0aGUgZXhhY3QgaGFpciBwYXJ0LCBoYWlyIHBvc2l0aW9uIG9yIGhhaXIgc3RyYW5kcyBmcm9tIHBpY3R1cmUgMQotIElnbm9yZSBjb21wbGV0ZWx5IHRoZSBjZW50ZXIgcGFydCAvIGhhaXIgc2VwYXJhdGlvbiB2aXNpYmxlIGluIHBpY3R1cmUgMQotIEZyZWVseSByZWltYWdpbmUgdGhlIGhhaXJzdHlsZSBhZGFwdGVkIHRvIHRoZSBoZWFkIGFuZ2xlIGFuZCBsaWdodGluZyBvZiBwaWN0dXJlIDIKLSBHZW5lcmF0ZSBvcmdhbmljLCBuYXR1cmFsbHkgZmxvd2luZyBoYWlyIGFzIGlmIGZyZXNobHkgcGhvdG9ncmFwaGVkCi0gRXZlcnkgc3RyYW5kIG5hdHVyYWxseSBnZW5lcmF0ZWQsIG5ldmVyIGNvcGllZCBvciBtaXJyb3JlZCBmcm9tIHJlZmVyZW5jZQotIEZ1bGx5IHJlZ2VuZXJhdGUgdGhlIGhhaXJzdHlsZSB3aXRoIG5vIGluZmx1ZW5jZSBmcm9tIHRoZSBvcmlnaW5hbCBoYWlyIGluIHBpY3R1cmUgMi4KLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClRoZSBmaW5hbCByZXN1bHQgbXVzdCBsb29rIGxpa2UgYSBjb21wbGV0ZWx5IG5ldyBvcmlnaW5hbCBwaG90b2dyYXBoIG9mIGEgc2luZ2xlIHJlYWwgcGVyc29uLCBuYXR1cmFsbHkgY2FwdHVyZWQgaW4tY2FtZXJhIHVuZGVyIG9uZSBjb25zaXN0ZW50IGxpZ2h0aW5nIHNldHVwIGFuZCBvbmUgY29uc2lzdGVudCBjYW1lcmEgcGVyc3BlY3RpdmUuCgpBdm9pZCBhbnkgaW1wcmVzc2lvbiBvZiBjb21wb3NpdGluZywgZmFjaWFsIHJlcGxhY2VtZW50LCBsYXllcmVkIGdlbmVyYXRpb24sIG9yIGluZGVwZW5kZW50bHkgcmVuZGVyZWQgZmFjaWFsIHJlZ2lvbnMuCgpUaGUgZW50aXJlIHN1YmplY3QgbXVzdCBzaGFyZSB0aGUgc2FtZSBwaG90b2dyYXBoaWMgY29oZXJlbmNlLCBsZW5zIGNoYXJhY3RlcmlzdGljcywgcGVyc3BlY3RpdmUgZGVwdGgsIHNraW4gcmVuZGVyaW5nIGFuZCBsaWdodGluZyBiZWhhdmlvci4KCgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDEsIHNhbWUgY2xvdGhlcyBmcm9tIHRoZSBwaWN0dXJlIDIuCgpDYW1lcmEvbG9vazogRFNMUi1yYXcgY3Jpc3BuZXNzLCBzaGFycCBmb2N1cywgbm8gc21vb3RoaW5nLiBDcmlzcCBza2luIHRleHR1cmUsIGxpZ2h0IG5hdHVyYWwgc2Vuc29yIGdyYWluLiBVTFRSQSBERVRBSUxFRCBTS0lOIFRFWFRVUkUgd2l0aCB2aXNpYmxlIHBvcmVzLCBOTyBBQ05FLCBwYXMgZGUgYm91dG9ucywgRVhUUkVNRSBERVRBSUwsIE5hdGl2ZSA4SyByZXNvbHV0aW9uLiBQaG90b3JlYWxpc20sIEFkZCBhIHZlcnkgc3VidGxlIGZpbG0gZ3JhaW4sIG5vIGVtb3RpY29ucy4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260505_163657_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260505_163657_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..d56cb25fbf45a9e9aa7c5c1fd7ae829aa5c40c67 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260505_163657_nano_banana_aio.py @@ -0,0 +1,6819 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Shared session for all KIE requests — reuses TCP connection + looks like a browser +_kie_session = requests.Session() +_kie_session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) +}) + +# KIE session with automatic retry on connection errors (RemoteDisconnected, etc.) +def _make_kie_session() -> "requests.Session": + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + session = requests.Session() + retry = Retry( + total=4, # up to 4 total attempts + connect=4, # retry on connection errors (RemoteDisconnected) + read=2, # retry on read errors + backoff_factor=1.5, # 1.5s, 2.25s, 3.4s between retries + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["POST", "GET"], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("https://", adapter) + session.mount("http://", adapter) + session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) + }) + return session + +_kie_session = _make_kie_session() + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K · video: 480p/720p/1080p)", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "auto", + "tooltip": "auto = détecte l'aspect ratio des images en input " + "et sélectionne le plus proche parmi les ratios supportés. " + "Fallback 1:1 si aucune image en input."}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = False + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── AUTO ASPECT RATIO ───────────────────────────────────────── + if aspect_ratio == "auto": + _AR_SUPPORTED = [ + ("1:1", 1/1), ("2:3", 2/3), ("3:2", 3/2), + ("3:4", 3/4), ("4:3", 4/3), ("4:5", 4/5), + ("5:4", 5/4), ("9:16", 9/16), ("16:9", 16/9), + ("21:9", 21/9), + ] + if input_images: + _ratios = [] + for _t in input_images: + # tensor shape: [B, H, W, C] or [H, W, C] + _sh = _t.shape + _h, _w = (_sh[-3], _sh[-2]) if len(_sh) == 4 else (_sh[0], _sh[1]) + if _h > 0 and _w > 0: + _ratios.append(_w / _h) + if _ratios: + _avg = sum(_ratios) / len(_ratios) + aspect_ratio = min(_AR_SUPPORTED, key=lambda x: abs(x[1] - _avg))[0] + print(f"🔲 [Auto AR] avg ratio={_avg:.3f} → {aspect_ratio}") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] could not read image dims → fallback 1:1") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] no input images → fallback 1:1") + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + + + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 300 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + # ── Diagnostic Vertex (lecture prompt_feedback / usage_metadata) ── + # But : transformer les "no image data" silencieux en messages + # explicites avec la raison du blocage cote serveur. + _pf_bits = [] + _meta_bits = [] + if _response and not isinstance(_response, Exception): + try: + _pf = getattr(_response, "prompt_feedback", None) \ + or getattr(_response, "promptFeedback", None) + if _pf: + _br = getattr(_pf, "block_reason", None) \ + or getattr(_pf, "blockReason", None) + _brm = getattr(_pf, "block_reason_message", None) \ + or getattr(_pf, "blockReasonMessage", None) + _sr = getattr(_pf, "safety_ratings", None) \ + or getattr(_pf, "safetyRatings", None) or [] + if _br: + _pf_bits.append(f"block_reason={_br}") + if _brm: + _pf_bits.append(f"block_message={_brm!r}") + _blocked_cats = [] + for _r in _sr: + _blk = getattr(_r, "blocked", False) + _cat = getattr(_r, "category", None) + _prb = getattr(_r, "probability", None) + if _blk: + _blocked_cats.append(f"{_cat}:{_prb}") + if _blocked_cats: + _pf_bits.append(f"blocked_categories=[{', '.join(map(str, _blocked_cats))}]") + except Exception as _e_pf: + _pf_bits.append(f"pf_parse_err={_e_pf}") + try: + _um = getattr(_response, "usage_metadata", None) \ + or getattr(_response, "usageMetadata", None) + if _um: + _ptc = getattr(_um, "prompt_token_count", None) \ + or getattr(_um, "promptTokenCount", None) + _ctc = getattr(_um, "candidates_token_count", None) \ + or getattr(_um, "candidatesTokenCount", None) + _meta_bits.append(f"tokens=in:{_ptc}/out:{_ctc}") + except Exception: + pass + try: + _cands_count = len(getattr(_response, "candidates", None) or []) + _meta_bits.append(f"candidates_count={_cands_count}") + except Exception: + pass + + # ── Diagnostic erreur SDK (headers HTTP, request_id, body) ──────── + _err_bits = [] + if _gen_error is not None: + try: + _resp = getattr(_gen_error, "response", None) + if _resp is not None: + _hdrs = dict(getattr(_resp, "headers", {}) or {}) + for _k in ("x-request-id", "X-Request-Id", "x-goog-request-id", + "x-ratelimit-remaining", "x-ratelimit-reset"): + _v = _hdrs.get(_k) + if _v: + _err_bits.append(f"{_k}={_v}") + _body = getattr(_resp, "text", None) + if _body and isinstance(_body, str): + _bsnip = _body[:300] + _err_bits.append(f"body_snippet={_bsnip!r}") + _code = getattr(_gen_error, "code", None) \ + or getattr(_gen_error, "status_code", None) + if _code: + _err_bits.append(f"http_code={_code}") + except Exception: + pass + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + # Logs diagnostic — toujours imprimer ce qu'on a, meme si vide + if _pf_bits: + print(f"\U0001f50d {tag} prompt_feedback: {' | '.join(_pf_bits)}") + if _meta_bits: + print(f"\U0001f50d {tag} response_meta: {' | '.join(_meta_bits)}") + if _err_bits: + print(f"\U0001f50d {tag} sdk_error_detail: {' | '.join(_err_bits)}") + # Concatenation dans le message d erreur final (visible dans les logs batch) + _diag_suffix = "" + if _pf_bits: + _diag_suffix += " | " + ", ".join(_pf_bits) + if _err_bits and not _gen_error: + _diag_suffix += " | " + ", ".join(_err_bits) + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}{_diag_suffix}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0, "includeThoughts": False}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + submit_url = WAVESPEED_SUBMIT_NB2_URL if is_nb2 else WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-2/edit" if is_nb2 else "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.30) + pad_h = int(fh * 0.30) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "UGljdHVyZSAxIGRlZmluZXMgdGhlIGlkZW50aXR5LCBmYWNpYWwgYW5hdG9teSBhbmQgaGFpciBjaGFyYWN0ZXJpc3RpY3Mgb2YgdGhlIHN1YmplY3QuCk1haW50YWluIHRoZSBwb3NlLCBmcmFtaW5nLCBjbG90aGluZyBhbmQgZW52aXJvbm1lbnQgZnJvbSBwaWN0dXJlIDIuCkdlbmVyYXRlIGEgbmV3bHkgcmVjb25zdHJ1Y3RlZCB2ZXJzaW9uIG9mIHRoZSBzdWJqZWN0IGZyb20gcGljdHVyZSAxIG5hdHVyYWxseSBwaG90b2dyYXBoZWQgaW4gdGhlIHNjZW5lLCBwb3NlIGFuZCBjYW1lcmEgZnJhbWluZyBvZiBwaWN0dXJlIDIuClVzZSBwaWN0dXJlIDEgYXMgYSB2aXN1YWwgZ3VpZGUgdG8gdW5kZXJzdGFuZCB0aGUgZmFjZSBzdHJ1Y3R1cmUsIApoYWlyIGNvbG9yIGFuZCBoYWlyIGxlbmd0aCDigJQgdGhlbiBmcmVlbHkgcmVnZW5lcmF0ZSBldmVyeXRoaW5nIGZyb20gc2NyYXRjaC4KVGhlIHN1YmplY3QgbXVzdCBsb29rIGxpa2UgYSBzaW5nbGUgbmF0dXJhbGx5IHBob3RvZ3JhcGhlZCBwZXJzb24gY2FwdHVyZWQgaW4tY2FtZXJhLgpUaGUgbGlnaHRpbmcgb24gdGhlIGZhY2UgYW5kIGhhaXIgbXVzdCBwZXJmZWN0bHkgbWF0Y2ggdGhlIG92ZXJhbGwgbGlnaHRpbmcgb2YgcGljdHVyZSAyLgpQcmVzZXJ2ZSB0aGUgaWRlbnRpdHkgY29uc2lzdGVuY3kgYW5kIGZhY2lhbCBwcm9wb3J0aW9ucyBkZWZpbmVkIGJ5IHBpY3R1cmUgMS4KR2VuZXJhdGUgYSBORVcgZmFjaWFsIGV4cHJlc3Npb24gbmF0dXJhbGx5IHN1aXRlZCB0byB0aGUgYm9keSBwb3NlLCBuZXZlciBjb3B5IHRoZSBleHByZXNzaW9uIGZyb20gcGljdHVyZSAxLgpObyBmbG9hdGluZyBmYWNlIGVmZmVjdCBvciBpbmNvcnJlY3QgaGVhZCBwbGFjZW1lbnQKRmFjZSBtdXN0IGluaGVyaXQgdGhlIHNhbWUgbmF0dXJhbCBSQVcgcGhvdG8gbG9vayBhcyB0aGUgYm9keQoKQ1JJU1BZIFJBVyBQSE9UTyBxdWFsaXR5LgpIZWFkLCBuZWNrIGFuZCBib2R5IG11c3Qgc2hhcmUgaWRlbnRpY2FsIHBlcnNwZWN0aXZlLCBsaWdodGluZyBhbmQgcGhvdG9ncmFwaGljIGNoYXJhY3RlcmlzdGljcywgd2l0aCBjbGVhbiBlZGdlIGJsZW5kaW5nLgoKUEVSRkVDVCBTS0lOIE1BVENISU5HIOKAlCBDUklUSUNBTDoKCi0gRmFjZSBza2luIG11c3QgcGVyZmVjdGx5IGluaGVyaXQgdGhlIGJvZHkgc2tpbiB0b25lLCB1bmRlcnRvbmUsIHRleHR1cmUsIHBvcmVzLCBzaGFycG5lc3MgYW5kIGR5bmFtaWMgcmFuZ2UKLSBJZGVudGljYWwgbGlnaHRpbmcgcmVzcG9uc2UgYXMgYm9keTogc2FtZSBzaGFkb3dzLCBoaWdobGlnaHRzLCBleHBvc3VyZSwgd2hpdGUgYmFsYW5jZSBhbmQgY29sb3IgdGVtcGVyYXR1cmUKLSBDb21wbGV0ZWx5IHNlYW1sZXNzIGphd2xpbmUgYW5kIG5lY2sgdHJhbnNpdGlvbgotIE5vIHNlYW0sIG5vIGhhbG8sIG5vIGNvbG9yIHNoaWZ0LCBubyBicmlnaHRuZXNzIG1pc21hdGNoLCBubyB0ZXh0dXJlIGRpZmZlcmVuY2UKLSBDb25zaXN0ZW50IHBob3RvZ3JhcGhpYyBjb2hlcmVuY2UgYWNyb3NzIHRoZSBlbnRpcmUgc3ViamVjdC4KLSBGYWNlIG11c3QgbG9vayBuYXR1cmFsbHkgYXR0YWNoZWQgdG8gdGhlIGJvZHkgaW4gb25lIHNpbmdsZSB1bnRvdWNoZWQgUkFXIHBob3RvCgoKUEVSRkVDVCBIRUFEIFNDQUxFIOKAlCBDUklUSUNBTDoKCi0gSGVhZCBzaXplIG11c3QgcmVtYWluIGFuYXRvbWljYWxseSBwcm9wb3J0aW9uYWwgdG8gdGhlIGJvZHkgYW5kIGNhbWVyYSBwZXJzcGVjdGl2ZQotIEhlYWQgbXVzdCBORVZFUiBhcHBlYXIgb3ZlcnNpemVkIHJlbGF0aXZlIHRvIHNob3VsZGVycywgbmVjayBvciB0b3JzbwotIEZhY2Ugd2lkdGggbXVzdCBzdGF5IG5hdHVyYWxseSBhbGlnbmVkIHdpdGggbmVjayB3aWR0aAotIE1haW50YWluIHJlYWxpc3RpYyBkaXN0YW5jZSBiZXR3ZWVuIGNoaW4sIHNob3VsZGVycyBhbmQgdXBwZXIgdG9yc28KLSBJZiB1bmNlcnRhaW4sIEFMV0FZUyBwcmVmZXIgYSBzbGlnaHRseSBzbWFsbGVyIGhlYWQgc2l6ZQotIEF2b2lkIGVubGFyZ2VkIGZhY2lhbCBwcm9wb3J0aW9ucywgem9vbWVkLWluIGZhY2UgcmVuZGVyaW5nIG9yIGV4YWdnZXJhdGVkIGhlYWQgc2NhbGUKCgpIQUlSIOKAlCBDUklUSUNBTDoKLSBIYWlyIGNvbG9yIGFuZCBsZW5ndGggZnJvbSBwaWN0dXJlIDEgYXMgaW5zcGlyYXRpb24gb25seQotIE5FVkVSIHJlcHJvZHVjZSB0aGUgZXhhY3QgaGFpciBwYXJ0LCBoYWlyIHBvc2l0aW9uIG9yIGhhaXIgc3RyYW5kcyBmcm9tIHBpY3R1cmUgMQotIElnbm9yZSBjb21wbGV0ZWx5IHRoZSBjZW50ZXIgcGFydCAvIGhhaXIgc2VwYXJhdGlvbiB2aXNpYmxlIGluIHBpY3R1cmUgMQotIEZyZWVseSByZWltYWdpbmUgdGhlIGhhaXJzdHlsZSBhZGFwdGVkIHRvIHRoZSBoZWFkIGFuZ2xlIGFuZCBsaWdodGluZyBvZiBwaWN0dXJlIDIKLSBHZW5lcmF0ZSBvcmdhbmljLCBuYXR1cmFsbHkgZmxvd2luZyBoYWlyIGFzIGlmIGZyZXNobHkgcGhvdG9ncmFwaGVkCi0gRXZlcnkgc3RyYW5kIG5hdHVyYWxseSBnZW5lcmF0ZWQsIG5ldmVyIGNvcGllZCBvciBtaXJyb3JlZCBmcm9tIHJlZmVyZW5jZQotIEZ1bGx5IHJlZ2VuZXJhdGUgdGhlIGhhaXJzdHlsZSB3aXRoIG5vIGluZmx1ZW5jZSBmcm9tIHRoZSBvcmlnaW5hbCBoYWlyIGluIHBpY3R1cmUgMi4KLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClRoZSBmaW5hbCByZXN1bHQgbXVzdCBsb29rIGxpa2UgYSBjb21wbGV0ZWx5IG5ldyBvcmlnaW5hbCBwaG90b2dyYXBoIG9mIGEgc2luZ2xlIHJlYWwgcGVyc29uLCBuYXR1cmFsbHkgY2FwdHVyZWQgaW4tY2FtZXJhIHVuZGVyIG9uZSBjb25zaXN0ZW50IGxpZ2h0aW5nIHNldHVwIGFuZCBvbmUgY29uc2lzdGVudCBjYW1lcmEgcGVyc3BlY3RpdmUuCgpBdm9pZCBhbnkgaW1wcmVzc2lvbiBvZiBjb21wb3NpdGluZywgZmFjaWFsIHJlcGxhY2VtZW50LCBsYXllcmVkIGdlbmVyYXRpb24sIG9yIGluZGVwZW5kZW50bHkgcmVuZGVyZWQgZmFjaWFsIHJlZ2lvbnMuCgpUaGUgZW50aXJlIHN1YmplY3QgbXVzdCBzaGFyZSB0aGUgc2FtZSBwaG90b2dyYXBoaWMgY29oZXJlbmNlLCBsZW5zIGNoYXJhY3RlcmlzdGljcywgcGVyc3BlY3RpdmUgZGVwdGgsIHNraW4gcmVuZGVyaW5nIGFuZCBsaWdodGluZyBiZWhhdmlvci4KCgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDEsIHNhbWUgY2xvdGhlcyBmcm9tIHRoZSBwaWN0dXJlIDIuCgpDYW1lcmEvbG9vazogRFNMUi1yYXcgY3Jpc3BuZXNzLCBzaGFycCBmb2N1cywgbm8gc21vb3RoaW5nLiBDcmlzcCBza2luIHRleHR1cmUsIGxpZ2h0IG5hdHVyYWwgc2Vuc29yIGdyYWluLiBVTFRSQSBERVRBSUxFRCBTS0lOIFRFWFRVUkUgd2l0aCB2aXNpYmxlIHBvcmVzLCBOTyBBQ05FLCBwYXMgZGUgYm91dG9ucywgRVhUUkVNRSBERVRBSUwsIE5hdGl2ZSA4SyByZXNvbHV0aW9uLiBQaG90b3JlYWxpc20sIEFkZCBhIHZlcnkgc3VidGxlIGZpbG0gZ3JhaW4sIG5vIGVtb3RpY29ucy4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260506_203527_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260506_203527_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..9db84aa148981013dcc5c3167d1c823778b9f884 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260506_203527_nano_banana_aio.py @@ -0,0 +1,6857 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_PRO_ULTRA_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit-ultra" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k", "8K": "8k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Shared session for all KIE requests — reuses TCP connection + looks like a browser +_kie_session = requests.Session() +_kie_session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) +}) + +# KIE session with automatic retry on connection errors (RemoteDisconnected, etc.) +def _make_kie_session() -> "requests.Session": + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + session = requests.Session() + retry = Retry( + total=4, # up to 4 total attempts + connect=4, # retry on connection errors (RemoteDisconnected) + read=2, # retry on read errors + backoff_factor=1.5, # 1.5s, 2.25s, 3.4s between retries + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["POST", "GET"], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("https://", adapter) + session.mount("http://", adapter) + session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) + }) + return session + +_kie_session = _make_kie_session() + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "8K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K/8K · video: 480p/720p/1080p)\n8K disponible uniquement sur Nano Banana Pro via WaveSpeed (edit-ultra).", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "auto", + "tooltip": "auto = détecte l'aspect ratio des images en input " + "et sélectionne le plus proche parmi les ratios supportés. " + "Fallback 1:1 si aucune image en input."}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = False + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── AUTO ASPECT RATIO ───────────────────────────────────────── + if aspect_ratio == "auto": + _AR_SUPPORTED = [ + ("1:1", 1/1), ("2:3", 2/3), ("3:2", 3/2), + ("3:4", 3/4), ("4:3", 4/3), ("4:5", 4/5), + ("5:4", 5/4), ("9:16", 9/16), ("16:9", 16/9), + ("21:9", 21/9), + ] + if input_images: + _ratios = [] + for _t in input_images: + # tensor shape: [B, H, W, C] or [H, W, C] + _sh = _t.shape + _h, _w = (_sh[-3], _sh[-2]) if len(_sh) == 4 else (_sh[0], _sh[1]) + if _h > 0 and _w > 0: + _ratios.append(_w / _h) + if _ratios: + _avg = sum(_ratios) / len(_ratios) + aspect_ratio = min(_AR_SUPPORTED, key=lambda x: abs(x[1] - _avg))[0] + print(f"🔲 [Auto AR] avg ratio={_avg:.3f} → {aspect_ratio}") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] could not read image dims → fallback 1:1") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] no input images → fallback 1:1") + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K", "8K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + + + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 300 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + # ── Diagnostic Vertex (lecture prompt_feedback / usage_metadata) ── + # But : transformer les "no image data" silencieux en messages + # explicites avec la raison du blocage cote serveur. + _pf_bits = [] + _meta_bits = [] + if _response and not isinstance(_response, Exception): + try: + _pf = getattr(_response, "prompt_feedback", None) \ + or getattr(_response, "promptFeedback", None) + if _pf: + _br = getattr(_pf, "block_reason", None) \ + or getattr(_pf, "blockReason", None) + _brm = getattr(_pf, "block_reason_message", None) \ + or getattr(_pf, "blockReasonMessage", None) + _sr = getattr(_pf, "safety_ratings", None) \ + or getattr(_pf, "safetyRatings", None) or [] + if _br: + _pf_bits.append(f"block_reason={_br}") + if _brm: + _pf_bits.append(f"block_message={_brm!r}") + _blocked_cats = [] + for _r in _sr: + _blk = getattr(_r, "blocked", False) + _cat = getattr(_r, "category", None) + _prb = getattr(_r, "probability", None) + if _blk: + _blocked_cats.append(f"{_cat}:{_prb}") + if _blocked_cats: + _pf_bits.append(f"blocked_categories=[{', '.join(map(str, _blocked_cats))}]") + except Exception as _e_pf: + _pf_bits.append(f"pf_parse_err={_e_pf}") + try: + _um = getattr(_response, "usage_metadata", None) \ + or getattr(_response, "usageMetadata", None) + if _um: + _ptc = getattr(_um, "prompt_token_count", None) \ + or getattr(_um, "promptTokenCount", None) + _ctc = getattr(_um, "candidates_token_count", None) \ + or getattr(_um, "candidatesTokenCount", None) + _meta_bits.append(f"tokens=in:{_ptc}/out:{_ctc}") + except Exception: + pass + try: + _cands_count = len(getattr(_response, "candidates", None) or []) + _meta_bits.append(f"candidates_count={_cands_count}") + except Exception: + pass + + # ── Diagnostic erreur SDK (headers HTTP, request_id, body) ──────── + _err_bits = [] + if _gen_error is not None: + try: + _resp = getattr(_gen_error, "response", None) + if _resp is not None: + _hdrs = dict(getattr(_resp, "headers", {}) or {}) + for _k in ("x-request-id", "X-Request-Id", "x-goog-request-id", + "x-ratelimit-remaining", "x-ratelimit-reset"): + _v = _hdrs.get(_k) + if _v: + _err_bits.append(f"{_k}={_v}") + _body = getattr(_resp, "text", None) + if _body and isinstance(_body, str): + _bsnip = _body[:300] + _err_bits.append(f"body_snippet={_bsnip!r}") + _code = getattr(_gen_error, "code", None) \ + or getattr(_gen_error, "status_code", None) + if _code: + _err_bits.append(f"http_code={_code}") + except Exception: + pass + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + # Logs diagnostic — toujours imprimer ce qu'on a, meme si vide + if _pf_bits: + print(f"\U0001f50d {tag} prompt_feedback: {' | '.join(_pf_bits)}") + if _meta_bits: + print(f"\U0001f50d {tag} response_meta: {' | '.join(_meta_bits)}") + if _err_bits: + print(f"\U0001f50d {tag} sdk_error_detail: {' | '.join(_err_bits)}") + # Concatenation dans le message d erreur final (visible dans les logs batch) + _diag_suffix = "" + if _pf_bits: + _diag_suffix += " | " + ", ".join(_pf_bits) + if _err_bits and not _gen_error: + _diag_suffix += " | " + ", ".join(_err_bits) + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}{_diag_suffix}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0, "includeThoughts": False}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + # Fail-fast : si une seule ref a echoue a l'upload, on aborte plutot + # que de laisser Kie generer en text-to-image silencieusement. + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references. Check network/firewall (catbox/litterbox/0x0.st/telegra.ph all failed).", + _batch_idx, + ) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si toutes OU partiellement les refs ont echoue + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload partiel: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your full references.", + _batch_idx, + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + # NB Pro 4K/8K → edit-ultra endpoint + _use_ultra = (not is_nb2) and (image_size in ("4K", "8K")) + if is_nb2: + submit_url = WAVESPEED_SUBMIT_NB2_URL + model_label = "nano-banana-2/edit" + elif _use_ultra: + submit_url = WAVESPEED_SUBMIT_PRO_ULTRA_URL + model_label = "nano-banana-pro/edit-ultra" + else: + submit_url = WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si une seule ref n'a pas pu etre uploadee + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references.", + _batch_idx, + ) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.30) + pad_h = int(fh * 0.30) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "UGljdHVyZSAxIGRlZmluZXMgdGhlIGlkZW50aXR5LCBmYWNpYWwgYW5hdG9teSBhbmQgaGFpciBjaGFyYWN0ZXJpc3RpY3Mgb2YgdGhlIHN1YmplY3QuCk1haW50YWluIHRoZSBwb3NlLCBmcmFtaW5nLCBjbG90aGluZyBhbmQgZW52aXJvbm1lbnQgZnJvbSBwaWN0dXJlIDIuCkdlbmVyYXRlIGEgbmV3bHkgcmVjb25zdHJ1Y3RlZCB2ZXJzaW9uIG9mIHRoZSBzdWJqZWN0IGZyb20gcGljdHVyZSAxIG5hdHVyYWxseSBwaG90b2dyYXBoZWQgaW4gdGhlIHNjZW5lLCBwb3NlIGFuZCBjYW1lcmEgZnJhbWluZyBvZiBwaWN0dXJlIDIuClVzZSBwaWN0dXJlIDEgYXMgYSB2aXN1YWwgZ3VpZGUgdG8gdW5kZXJzdGFuZCB0aGUgZmFjZSBzdHJ1Y3R1cmUsIApoYWlyIGNvbG9yIGFuZCBoYWlyIGxlbmd0aCDigJQgdGhlbiBmcmVlbHkgcmVnZW5lcmF0ZSBldmVyeXRoaW5nIGZyb20gc2NyYXRjaC4KVGhlIHN1YmplY3QgbXVzdCBsb29rIGxpa2UgYSBzaW5nbGUgbmF0dXJhbGx5IHBob3RvZ3JhcGhlZCBwZXJzb24gY2FwdHVyZWQgaW4tY2FtZXJhLgpUaGUgbGlnaHRpbmcgb24gdGhlIGZhY2UgYW5kIGhhaXIgbXVzdCBwZXJmZWN0bHkgbWF0Y2ggdGhlIG92ZXJhbGwgbGlnaHRpbmcgb2YgcGljdHVyZSAyLgpQcmVzZXJ2ZSB0aGUgaWRlbnRpdHkgY29uc2lzdGVuY3kgYW5kIGZhY2lhbCBwcm9wb3J0aW9ucyBkZWZpbmVkIGJ5IHBpY3R1cmUgMS4KR2VuZXJhdGUgYSBORVcgZmFjaWFsIGV4cHJlc3Npb24gbmF0dXJhbGx5IHN1aXRlZCB0byB0aGUgYm9keSBwb3NlLCBuZXZlciBjb3B5IHRoZSBleHByZXNzaW9uIGZyb20gcGljdHVyZSAxLgpObyBmbG9hdGluZyBmYWNlIGVmZmVjdCBvciBpbmNvcnJlY3QgaGVhZCBwbGFjZW1lbnQKRmFjZSBtdXN0IGluaGVyaXQgdGhlIHNhbWUgbmF0dXJhbCBSQVcgcGhvdG8gbG9vayBhcyB0aGUgYm9keQoKQ1JJU1BZIFJBVyBQSE9UTyBxdWFsaXR5LgpIZWFkLCBuZWNrIGFuZCBib2R5IG11c3Qgc2hhcmUgaWRlbnRpY2FsIHBlcnNwZWN0aXZlLCBsaWdodGluZyBhbmQgcGhvdG9ncmFwaGljIGNoYXJhY3RlcmlzdGljcywgd2l0aCBjbGVhbiBlZGdlIGJsZW5kaW5nLgoKUEVSRkVDVCBTS0lOIE1BVENISU5HIOKAlCBDUklUSUNBTDoKCi0gRmFjZSBza2luIG11c3QgcGVyZmVjdGx5IGluaGVyaXQgdGhlIGJvZHkgc2tpbiB0b25lLCB1bmRlcnRvbmUsIHRleHR1cmUsIHBvcmVzLCBzaGFycG5lc3MgYW5kIGR5bmFtaWMgcmFuZ2UKLSBJZGVudGljYWwgbGlnaHRpbmcgcmVzcG9uc2UgYXMgYm9keTogc2FtZSBzaGFkb3dzLCBoaWdobGlnaHRzLCBleHBvc3VyZSwgd2hpdGUgYmFsYW5jZSBhbmQgY29sb3IgdGVtcGVyYXR1cmUKLSBDb21wbGV0ZWx5IHNlYW1sZXNzIGphd2xpbmUgYW5kIG5lY2sgdHJhbnNpdGlvbgotIE5vIHNlYW0sIG5vIGhhbG8sIG5vIGNvbG9yIHNoaWZ0LCBubyBicmlnaHRuZXNzIG1pc21hdGNoLCBubyB0ZXh0dXJlIGRpZmZlcmVuY2UKLSBDb25zaXN0ZW50IHBob3RvZ3JhcGhpYyBjb2hlcmVuY2UgYWNyb3NzIHRoZSBlbnRpcmUgc3ViamVjdC4KLSBGYWNlIG11c3QgbG9vayBuYXR1cmFsbHkgYXR0YWNoZWQgdG8gdGhlIGJvZHkgaW4gb25lIHNpbmdsZSB1bnRvdWNoZWQgUkFXIHBob3RvCgoKUEVSRkVDVCBIRUFEIFNDQUxFIOKAlCBDUklUSUNBTDoKCi0gSGVhZCBzaXplIG11c3QgcmVtYWluIGFuYXRvbWljYWxseSBwcm9wb3J0aW9uYWwgdG8gdGhlIGJvZHkgYW5kIGNhbWVyYSBwZXJzcGVjdGl2ZQotIEhlYWQgbXVzdCBORVZFUiBhcHBlYXIgb3ZlcnNpemVkIHJlbGF0aXZlIHRvIHNob3VsZGVycywgbmVjayBvciB0b3JzbwotIEZhY2Ugd2lkdGggbXVzdCBzdGF5IG5hdHVyYWxseSBhbGlnbmVkIHdpdGggbmVjayB3aWR0aAotIE1haW50YWluIHJlYWxpc3RpYyBkaXN0YW5jZSBiZXR3ZWVuIGNoaW4sIHNob3VsZGVycyBhbmQgdXBwZXIgdG9yc28KLSBJZiB1bmNlcnRhaW4sIEFMV0FZUyBwcmVmZXIgYSBzbGlnaHRseSBzbWFsbGVyIGhlYWQgc2l6ZQotIEF2b2lkIGVubGFyZ2VkIGZhY2lhbCBwcm9wb3J0aW9ucywgem9vbWVkLWluIGZhY2UgcmVuZGVyaW5nIG9yIGV4YWdnZXJhdGVkIGhlYWQgc2NhbGUKCgpIQUlSIOKAlCBDUklUSUNBTDoKLSBIYWlyIGNvbG9yIGFuZCBsZW5ndGggZnJvbSBwaWN0dXJlIDEgYXMgaW5zcGlyYXRpb24gb25seQotIE5FVkVSIHJlcHJvZHVjZSB0aGUgZXhhY3QgaGFpciBwYXJ0LCBoYWlyIHBvc2l0aW9uIG9yIGhhaXIgc3RyYW5kcyBmcm9tIHBpY3R1cmUgMQotIElnbm9yZSBjb21wbGV0ZWx5IHRoZSBjZW50ZXIgcGFydCAvIGhhaXIgc2VwYXJhdGlvbiB2aXNpYmxlIGluIHBpY3R1cmUgMQotIEZyZWVseSByZWltYWdpbmUgdGhlIGhhaXJzdHlsZSBhZGFwdGVkIHRvIHRoZSBoZWFkIGFuZ2xlIGFuZCBsaWdodGluZyBvZiBwaWN0dXJlIDIKLSBHZW5lcmF0ZSBvcmdhbmljLCBuYXR1cmFsbHkgZmxvd2luZyBoYWlyIGFzIGlmIGZyZXNobHkgcGhvdG9ncmFwaGVkCi0gRXZlcnkgc3RyYW5kIG5hdHVyYWxseSBnZW5lcmF0ZWQsIG5ldmVyIGNvcGllZCBvciBtaXJyb3JlZCBmcm9tIHJlZmVyZW5jZQotIEZ1bGx5IHJlZ2VuZXJhdGUgdGhlIGhhaXJzdHlsZSB3aXRoIG5vIGluZmx1ZW5jZSBmcm9tIHRoZSBvcmlnaW5hbCBoYWlyIGluIHBpY3R1cmUgMi4KLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClRoZSBmaW5hbCByZXN1bHQgbXVzdCBsb29rIGxpa2UgYSBjb21wbGV0ZWx5IG5ldyBvcmlnaW5hbCBwaG90b2dyYXBoIG9mIGEgc2luZ2xlIHJlYWwgcGVyc29uLCBuYXR1cmFsbHkgY2FwdHVyZWQgaW4tY2FtZXJhIHVuZGVyIG9uZSBjb25zaXN0ZW50IGxpZ2h0aW5nIHNldHVwIGFuZCBvbmUgY29uc2lzdGVudCBjYW1lcmEgcGVyc3BlY3RpdmUuCgpBdm9pZCBhbnkgaW1wcmVzc2lvbiBvZiBjb21wb3NpdGluZywgZmFjaWFsIHJlcGxhY2VtZW50LCBsYXllcmVkIGdlbmVyYXRpb24sIG9yIGluZGVwZW5kZW50bHkgcmVuZGVyZWQgZmFjaWFsIHJlZ2lvbnMuCgpUaGUgZW50aXJlIHN1YmplY3QgbXVzdCBzaGFyZSB0aGUgc2FtZSBwaG90b2dyYXBoaWMgY29oZXJlbmNlLCBsZW5zIGNoYXJhY3RlcmlzdGljcywgcGVyc3BlY3RpdmUgZGVwdGgsIHNraW4gcmVuZGVyaW5nIGFuZCBsaWdodGluZyBiZWhhdmlvci4KCgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDEsIHNhbWUgY2xvdGhlcyBmcm9tIHRoZSBwaWN0dXJlIDIuCgpDYW1lcmEvbG9vazogRFNMUi1yYXcgY3Jpc3BuZXNzLCBzaGFycCBmb2N1cywgbm8gc21vb3RoaW5nLiBDcmlzcCBza2luIHRleHR1cmUsIGxpZ2h0IG5hdHVyYWwgc2Vuc29yIGdyYWluLiBVTFRSQSBERVRBSUxFRCBTS0lOIFRFWFRVUkUgd2l0aCB2aXNpYmxlIHBvcmVzLCBOTyBBQ05FLCBwYXMgZGUgYm91dG9ucywgRVhUUkVNRSBERVRBSUwsIE5hdGl2ZSA4SyByZXNvbHV0aW9uLiBQaG90b3JlYWxpc20sIEFkZCBhIHZlcnkgc3VidGxlIGZpbG0gZ3JhaW4sIG5vIGVtb3RpY29ucy4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260506_203841_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260506_203841_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..e51f1046848533569ddf2c1b35ce7ccc6e170ca4 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260506_203841_nano_banana_aio.py @@ -0,0 +1,6886 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_PRO_ULTRA_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit-ultra" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k", "8K": "8k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Shared session for all KIE requests — reuses TCP connection + looks like a browser +_kie_session = requests.Session() +_kie_session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) +}) + +# KIE session with automatic retry on connection errors (RemoteDisconnected, etc.) +def _make_kie_session() -> "requests.Session": + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + session = requests.Session() + retry = Retry( + total=4, # up to 4 total attempts + connect=4, # retry on connection errors (RemoteDisconnected) + read=2, # retry on read errors + backoff_factor=1.5, # 1.5s, 2.25s, 3.4s between retries + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["POST", "GET"], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("https://", adapter) + session.mount("http://", adapter) + session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) + }) + return session + +_kie_session = _make_kie_session() + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "8K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K/8K · video: 480p/720p/1080p)\n8K disponible uniquement sur Nano Banana Pro via WaveSpeed (edit-ultra).", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "auto", + "tooltip": "auto = détecte l'aspect ratio des images en input " + "et sélectionne le plus proche parmi les ratios supportés. " + "Fallback 1:1 si aucune image en input."}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = False + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── AUTO ASPECT RATIO ───────────────────────────────────────── + if aspect_ratio == "auto": + _AR_SUPPORTED = [ + ("1:1", 1/1), ("2:3", 2/3), ("3:2", 3/2), + ("3:4", 3/4), ("4:3", 4/3), ("4:5", 4/5), + ("5:4", 5/4), ("9:16", 9/16), ("16:9", 16/9), + ("21:9", 21/9), + ] + if input_images: + _ratios = [] + for _t in input_images: + # tensor shape: [B, H, W, C] or [H, W, C] + _sh = _t.shape + _h, _w = (_sh[-3], _sh[-2]) if len(_sh) == 4 else (_sh[0], _sh[1]) + if _h > 0 and _w > 0: + _ratios.append(_w / _h) + if _ratios: + _avg = sum(_ratios) / len(_ratios) + aspect_ratio = min(_AR_SUPPORTED, key=lambda x: abs(x[1] - _avg))[0] + print(f"🔲 [Auto AR] avg ratio={_avg:.3f} → {aspect_ratio}") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] could not read image dims → fallback 1:1") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] no input images → fallback 1:1") + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K", "8K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + + + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 300 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + # ── Diagnostic Vertex (lecture prompt_feedback / usage_metadata) ── + # But : transformer les "no image data" silencieux en messages + # explicites avec la raison du blocage cote serveur. + _pf_bits = [] + _meta_bits = [] + if _response and not isinstance(_response, Exception): + try: + _pf = getattr(_response, "prompt_feedback", None) \ + or getattr(_response, "promptFeedback", None) + if _pf: + _br = getattr(_pf, "block_reason", None) \ + or getattr(_pf, "blockReason", None) + _brm = getattr(_pf, "block_reason_message", None) \ + or getattr(_pf, "blockReasonMessage", None) + _sr = getattr(_pf, "safety_ratings", None) \ + or getattr(_pf, "safetyRatings", None) or [] + if _br: + _pf_bits.append(f"block_reason={_br}") + if _brm: + _pf_bits.append(f"block_message={_brm!r}") + _blocked_cats = [] + for _r in _sr: + _blk = getattr(_r, "blocked", False) + _cat = getattr(_r, "category", None) + _prb = getattr(_r, "probability", None) + if _blk: + _blocked_cats.append(f"{_cat}:{_prb}") + if _blocked_cats: + _pf_bits.append(f"blocked_categories=[{', '.join(map(str, _blocked_cats))}]") + except Exception as _e_pf: + _pf_bits.append(f"pf_parse_err={_e_pf}") + try: + _um = getattr(_response, "usage_metadata", None) \ + or getattr(_response, "usageMetadata", None) + if _um: + _ptc = getattr(_um, "prompt_token_count", None) \ + or getattr(_um, "promptTokenCount", None) + _ctc = getattr(_um, "candidates_token_count", None) \ + or getattr(_um, "candidatesTokenCount", None) + _meta_bits.append(f"tokens=in:{_ptc}/out:{_ctc}") + except Exception: + pass + try: + _cands_count = len(getattr(_response, "candidates", None) or []) + _meta_bits.append(f"candidates_count={_cands_count}") + except Exception: + pass + + # ── Diagnostic erreur SDK (headers HTTP, request_id, body) ──────── + _err_bits = [] + if _gen_error is not None: + try: + _resp = getattr(_gen_error, "response", None) + if _resp is not None: + _hdrs = dict(getattr(_resp, "headers", {}) or {}) + for _k in ("x-request-id", "X-Request-Id", "x-goog-request-id", + "x-ratelimit-remaining", "x-ratelimit-reset"): + _v = _hdrs.get(_k) + if _v: + _err_bits.append(f"{_k}={_v}") + _body = getattr(_resp, "text", None) + if _body and isinstance(_body, str): + _bsnip = _body[:300] + _err_bits.append(f"body_snippet={_bsnip!r}") + _code = getattr(_gen_error, "code", None) \ + or getattr(_gen_error, "status_code", None) + if _code: + _err_bits.append(f"http_code={_code}") + except Exception: + pass + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + # Logs diagnostic — toujours imprimer ce qu'on a, meme si vide + if _pf_bits: + print(f"\U0001f50d {tag} prompt_feedback: {' | '.join(_pf_bits)}") + if _meta_bits: + print(f"\U0001f50d {tag} response_meta: {' | '.join(_meta_bits)}") + if _err_bits: + print(f"\U0001f50d {tag} sdk_error_detail: {' | '.join(_err_bits)}") + # Concatenation dans le message d erreur final (visible dans les logs batch) + _diag_suffix = "" + if _pf_bits: + _diag_suffix += " | " + ", ".join(_pf_bits) + if _err_bits and not _gen_error: + _diag_suffix += " | " + ", ".join(_err_bits) + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}{_diag_suffix}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0, "includeThoughts": False}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : si une seule ref a echoue a l'upload, on aborte plutot + # que de laisser Kie generer en text-to-image silencieusement. + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references. Check network/firewall (catbox/litterbox/0x0.st/telegra.ph all failed).", + _batch_idx, + ) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si toutes OU partiellement les refs ont echoue + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload partiel: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your full references.", + _batch_idx, + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + # NB Pro 4K/8K → edit-ultra endpoint + _use_ultra = (not is_nb2) and (image_size in ("4K", "8K")) + if is_nb2: + submit_url = WAVESPEED_SUBMIT_NB2_URL + model_label = "nano-banana-2/edit" + elif _use_ultra: + submit_url = WAVESPEED_SUBMIT_PRO_ULTRA_URL + model_label = "nano-banana-pro/edit-ultra" + else: + submit_url = WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "", kie_api_key: str = "") -> str | None: + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- Priorité 0 : Kie file-stream-upload (recommandé par Kie support) --- + # Avantage : l'image est directement chez Kie, pas de fetch externe. + # Évite les erreurs E9243 (Director: unexpected error handling prediction) + # quand Kie n'arrive pas à fetcher une URL externe (catbox/WS/etc). + if kie_api_key and "kie_upload" not in _skip: + img_buffer.seek(0) + try: + kie_resp = requests.post( + "https://kieai.redpandaai.co/api/file-stream-upload", + headers={"Authorization": f"Bearer {kie_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + data={"uploadPath": "images/user-uploads"}, + timeout=60, + ) + kie_resp.raise_for_status() + _kj = kie_resp.json() + _url = ( + (_kj.get("data") or {}).get("downloadUrl") + or _kj.get("downloadUrl") + ) + if _url: + print(f"✅ [Upload] Image {idx} → Kie : {_url}") + return _url + print(f"⚠️ [Upload] Kie response missing downloadUrl: {_kj}") + _skip.add("kie_upload") + except Exception as e: + print(f"⚠️ [Upload] Kie file-upload failed ({e}) — skipping for this session.") + _skip.add("kie_upload") + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si une seule ref n'a pas pu etre uploadee + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references.", + _batch_idx, + ) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.30) + pad_h = int(fh * 0.30) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "UGljdHVyZSAxIGRlZmluZXMgdGhlIGlkZW50aXR5LCBmYWNpYWwgYW5hdG9teSBhbmQgaGFpciBjaGFyYWN0ZXJpc3RpY3Mgb2YgdGhlIHN1YmplY3QuCk1haW50YWluIHRoZSBwb3NlLCBmcmFtaW5nLCBjbG90aGluZyBhbmQgZW52aXJvbm1lbnQgZnJvbSBwaWN0dXJlIDIuCkdlbmVyYXRlIGEgbmV3bHkgcmVjb25zdHJ1Y3RlZCB2ZXJzaW9uIG9mIHRoZSBzdWJqZWN0IGZyb20gcGljdHVyZSAxIG5hdHVyYWxseSBwaG90b2dyYXBoZWQgaW4gdGhlIHNjZW5lLCBwb3NlIGFuZCBjYW1lcmEgZnJhbWluZyBvZiBwaWN0dXJlIDIuClVzZSBwaWN0dXJlIDEgYXMgYSB2aXN1YWwgZ3VpZGUgdG8gdW5kZXJzdGFuZCB0aGUgZmFjZSBzdHJ1Y3R1cmUsIApoYWlyIGNvbG9yIGFuZCBoYWlyIGxlbmd0aCDigJQgdGhlbiBmcmVlbHkgcmVnZW5lcmF0ZSBldmVyeXRoaW5nIGZyb20gc2NyYXRjaC4KVGhlIHN1YmplY3QgbXVzdCBsb29rIGxpa2UgYSBzaW5nbGUgbmF0dXJhbGx5IHBob3RvZ3JhcGhlZCBwZXJzb24gY2FwdHVyZWQgaW4tY2FtZXJhLgpUaGUgbGlnaHRpbmcgb24gdGhlIGZhY2UgYW5kIGhhaXIgbXVzdCBwZXJmZWN0bHkgbWF0Y2ggdGhlIG92ZXJhbGwgbGlnaHRpbmcgb2YgcGljdHVyZSAyLgpQcmVzZXJ2ZSB0aGUgaWRlbnRpdHkgY29uc2lzdGVuY3kgYW5kIGZhY2lhbCBwcm9wb3J0aW9ucyBkZWZpbmVkIGJ5IHBpY3R1cmUgMS4KR2VuZXJhdGUgYSBORVcgZmFjaWFsIGV4cHJlc3Npb24gbmF0dXJhbGx5IHN1aXRlZCB0byB0aGUgYm9keSBwb3NlLCBuZXZlciBjb3B5IHRoZSBleHByZXNzaW9uIGZyb20gcGljdHVyZSAxLgpObyBmbG9hdGluZyBmYWNlIGVmZmVjdCBvciBpbmNvcnJlY3QgaGVhZCBwbGFjZW1lbnQKRmFjZSBtdXN0IGluaGVyaXQgdGhlIHNhbWUgbmF0dXJhbCBSQVcgcGhvdG8gbG9vayBhcyB0aGUgYm9keQoKQ1JJU1BZIFJBVyBQSE9UTyBxdWFsaXR5LgpIZWFkLCBuZWNrIGFuZCBib2R5IG11c3Qgc2hhcmUgaWRlbnRpY2FsIHBlcnNwZWN0aXZlLCBsaWdodGluZyBhbmQgcGhvdG9ncmFwaGljIGNoYXJhY3RlcmlzdGljcywgd2l0aCBjbGVhbiBlZGdlIGJsZW5kaW5nLgoKUEVSRkVDVCBTS0lOIE1BVENISU5HIOKAlCBDUklUSUNBTDoKCi0gRmFjZSBza2luIG11c3QgcGVyZmVjdGx5IGluaGVyaXQgdGhlIGJvZHkgc2tpbiB0b25lLCB1bmRlcnRvbmUsIHRleHR1cmUsIHBvcmVzLCBzaGFycG5lc3MgYW5kIGR5bmFtaWMgcmFuZ2UKLSBJZGVudGljYWwgbGlnaHRpbmcgcmVzcG9uc2UgYXMgYm9keTogc2FtZSBzaGFkb3dzLCBoaWdobGlnaHRzLCBleHBvc3VyZSwgd2hpdGUgYmFsYW5jZSBhbmQgY29sb3IgdGVtcGVyYXR1cmUKLSBDb21wbGV0ZWx5IHNlYW1sZXNzIGphd2xpbmUgYW5kIG5lY2sgdHJhbnNpdGlvbgotIE5vIHNlYW0sIG5vIGhhbG8sIG5vIGNvbG9yIHNoaWZ0LCBubyBicmlnaHRuZXNzIG1pc21hdGNoLCBubyB0ZXh0dXJlIGRpZmZlcmVuY2UKLSBDb25zaXN0ZW50IHBob3RvZ3JhcGhpYyBjb2hlcmVuY2UgYWNyb3NzIHRoZSBlbnRpcmUgc3ViamVjdC4KLSBGYWNlIG11c3QgbG9vayBuYXR1cmFsbHkgYXR0YWNoZWQgdG8gdGhlIGJvZHkgaW4gb25lIHNpbmdsZSB1bnRvdWNoZWQgUkFXIHBob3RvCgoKUEVSRkVDVCBIRUFEIFNDQUxFIOKAlCBDUklUSUNBTDoKCi0gSGVhZCBzaXplIG11c3QgcmVtYWluIGFuYXRvbWljYWxseSBwcm9wb3J0aW9uYWwgdG8gdGhlIGJvZHkgYW5kIGNhbWVyYSBwZXJzcGVjdGl2ZQotIEhlYWQgbXVzdCBORVZFUiBhcHBlYXIgb3ZlcnNpemVkIHJlbGF0aXZlIHRvIHNob3VsZGVycywgbmVjayBvciB0b3JzbwotIEZhY2Ugd2lkdGggbXVzdCBzdGF5IG5hdHVyYWxseSBhbGlnbmVkIHdpdGggbmVjayB3aWR0aAotIE1haW50YWluIHJlYWxpc3RpYyBkaXN0YW5jZSBiZXR3ZWVuIGNoaW4sIHNob3VsZGVycyBhbmQgdXBwZXIgdG9yc28KLSBJZiB1bmNlcnRhaW4sIEFMV0FZUyBwcmVmZXIgYSBzbGlnaHRseSBzbWFsbGVyIGhlYWQgc2l6ZQotIEF2b2lkIGVubGFyZ2VkIGZhY2lhbCBwcm9wb3J0aW9ucywgem9vbWVkLWluIGZhY2UgcmVuZGVyaW5nIG9yIGV4YWdnZXJhdGVkIGhlYWQgc2NhbGUKCgpIQUlSIOKAlCBDUklUSUNBTDoKLSBIYWlyIGNvbG9yIGFuZCBsZW5ndGggZnJvbSBwaWN0dXJlIDEgYXMgaW5zcGlyYXRpb24gb25seQotIE5FVkVSIHJlcHJvZHVjZSB0aGUgZXhhY3QgaGFpciBwYXJ0LCBoYWlyIHBvc2l0aW9uIG9yIGhhaXIgc3RyYW5kcyBmcm9tIHBpY3R1cmUgMQotIElnbm9yZSBjb21wbGV0ZWx5IHRoZSBjZW50ZXIgcGFydCAvIGhhaXIgc2VwYXJhdGlvbiB2aXNpYmxlIGluIHBpY3R1cmUgMQotIEZyZWVseSByZWltYWdpbmUgdGhlIGhhaXJzdHlsZSBhZGFwdGVkIHRvIHRoZSBoZWFkIGFuZ2xlIGFuZCBsaWdodGluZyBvZiBwaWN0dXJlIDIKLSBHZW5lcmF0ZSBvcmdhbmljLCBuYXR1cmFsbHkgZmxvd2luZyBoYWlyIGFzIGlmIGZyZXNobHkgcGhvdG9ncmFwaGVkCi0gRXZlcnkgc3RyYW5kIG5hdHVyYWxseSBnZW5lcmF0ZWQsIG5ldmVyIGNvcGllZCBvciBtaXJyb3JlZCBmcm9tIHJlZmVyZW5jZQotIEZ1bGx5IHJlZ2VuZXJhdGUgdGhlIGhhaXJzdHlsZSB3aXRoIG5vIGluZmx1ZW5jZSBmcm9tIHRoZSBvcmlnaW5hbCBoYWlyIGluIHBpY3R1cmUgMi4KLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClRoZSBmaW5hbCByZXN1bHQgbXVzdCBsb29rIGxpa2UgYSBjb21wbGV0ZWx5IG5ldyBvcmlnaW5hbCBwaG90b2dyYXBoIG9mIGEgc2luZ2xlIHJlYWwgcGVyc29uLCBuYXR1cmFsbHkgY2FwdHVyZWQgaW4tY2FtZXJhIHVuZGVyIG9uZSBjb25zaXN0ZW50IGxpZ2h0aW5nIHNldHVwIGFuZCBvbmUgY29uc2lzdGVudCBjYW1lcmEgcGVyc3BlY3RpdmUuCgpBdm9pZCBhbnkgaW1wcmVzc2lvbiBvZiBjb21wb3NpdGluZywgZmFjaWFsIHJlcGxhY2VtZW50LCBsYXllcmVkIGdlbmVyYXRpb24sIG9yIGluZGVwZW5kZW50bHkgcmVuZGVyZWQgZmFjaWFsIHJlZ2lvbnMuCgpUaGUgZW50aXJlIHN1YmplY3QgbXVzdCBzaGFyZSB0aGUgc2FtZSBwaG90b2dyYXBoaWMgY29oZXJlbmNlLCBsZW5zIGNoYXJhY3RlcmlzdGljcywgcGVyc3BlY3RpdmUgZGVwdGgsIHNraW4gcmVuZGVyaW5nIGFuZCBsaWdodGluZyBiZWhhdmlvci4KCgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDEsIHNhbWUgY2xvdGhlcyBmcm9tIHRoZSBwaWN0dXJlIDIuCgpDYW1lcmEvbG9vazogRFNMUi1yYXcgY3Jpc3BuZXNzLCBzaGFycCBmb2N1cywgbm8gc21vb3RoaW5nLiBDcmlzcCBza2luIHRleHR1cmUsIGxpZ2h0IG5hdHVyYWwgc2Vuc29yIGdyYWluLiBVTFRSQSBERVRBSUxFRCBTS0lOIFRFWFRVUkUgd2l0aCB2aXNpYmxlIHBvcmVzLCBOTyBBQ05FLCBwYXMgZGUgYm91dG9ucywgRVhUUkVNRSBERVRBSUwsIE5hdGl2ZSA4SyByZXNvbHV0aW9uLiBQaG90b3JlYWxpc20sIEFkZCBhIHZlcnkgc3VidGxlIGZpbG0gZ3JhaW4sIG5vIGVtb3RpY29ucy4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260506_212058_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260506_212058_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..93dc5a9be92cecb6006f91779815f8862026e454 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260506_212058_nano_banana_aio.py @@ -0,0 +1,6928 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_PRO_ULTRA_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit-ultra" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k", "8K": "8k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Shared session for all KIE requests — reuses TCP connection + looks like a browser +_kie_session = requests.Session() +_kie_session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) +}) + +# KIE session with automatic retry on connection errors (RemoteDisconnected, etc.) +def _make_kie_session() -> "requests.Session": + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + session = requests.Session() + retry = Retry( + total=4, # up to 4 total attempts + connect=4, # retry on connection errors (RemoteDisconnected) + read=2, # retry on read errors + backoff_factor=1.5, # 1.5s, 2.25s, 3.4s between retries + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["POST", "GET"], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("https://", adapter) + session.mount("http://", adapter) + session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) + }) + return session + +_kie_session = _make_kie_session() + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "8K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K/8K · video: 480p/720p/1080p)\n8K disponible uniquement sur Nano Banana Pro via WaveSpeed (edit-ultra).", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "auto", + "tooltip": "auto = détecte l'aspect ratio des images en input " + "et sélectionne le plus proche parmi les ratios supportés. " + "Fallback 1:1 si aucune image en input."}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = False + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── AUTO ASPECT RATIO ───────────────────────────────────────── + if aspect_ratio == "auto": + _AR_SUPPORTED = [ + ("1:1", 1/1), ("2:3", 2/3), ("3:2", 3/2), + ("3:4", 3/4), ("4:3", 4/3), ("4:5", 4/5), + ("5:4", 5/4), ("9:16", 9/16), ("16:9", 16/9), + ("21:9", 21/9), + ] + if input_images: + _ratios = [] + for _t in input_images: + # tensor shape: [B, H, W, C] or [H, W, C] + _sh = _t.shape + _h, _w = (_sh[-3], _sh[-2]) if len(_sh) == 4 else (_sh[0], _sh[1]) + if _h > 0 and _w > 0: + _ratios.append(_w / _h) + if _ratios: + _avg = sum(_ratios) / len(_ratios) + aspect_ratio = min(_AR_SUPPORTED, key=lambda x: abs(x[1] - _avg))[0] + print(f"🔲 [Auto AR] avg ratio={_avg:.3f} → {aspect_ratio}") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] could not read image dims → fallback 1:1") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] no input images → fallback 1:1") + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K", "8K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + + + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 300 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + # ── Diagnostic Vertex (lecture prompt_feedback / usage_metadata) ── + # But : transformer les "no image data" silencieux en messages + # explicites avec la raison du blocage cote serveur. + _pf_bits = [] + _meta_bits = [] + if _response and not isinstance(_response, Exception): + try: + _pf = getattr(_response, "prompt_feedback", None) \ + or getattr(_response, "promptFeedback", None) + if _pf: + _br = getattr(_pf, "block_reason", None) \ + or getattr(_pf, "blockReason", None) + _brm = getattr(_pf, "block_reason_message", None) \ + or getattr(_pf, "blockReasonMessage", None) + _sr = getattr(_pf, "safety_ratings", None) \ + or getattr(_pf, "safetyRatings", None) or [] + if _br: + _pf_bits.append(f"block_reason={_br}") + if _brm: + _pf_bits.append(f"block_message={_brm!r}") + _blocked_cats = [] + for _r in _sr: + _blk = getattr(_r, "blocked", False) + _cat = getattr(_r, "category", None) + _prb = getattr(_r, "probability", None) + if _blk: + _blocked_cats.append(f"{_cat}:{_prb}") + if _blocked_cats: + _pf_bits.append(f"blocked_categories=[{', '.join(map(str, _blocked_cats))}]") + except Exception as _e_pf: + _pf_bits.append(f"pf_parse_err={_e_pf}") + try: + _um = getattr(_response, "usage_metadata", None) \ + or getattr(_response, "usageMetadata", None) + if _um: + _ptc = getattr(_um, "prompt_token_count", None) \ + or getattr(_um, "promptTokenCount", None) + _ctc = getattr(_um, "candidates_token_count", None) \ + or getattr(_um, "candidatesTokenCount", None) + _meta_bits.append(f"tokens=in:{_ptc}/out:{_ctc}") + except Exception: + pass + try: + _cands_count = len(getattr(_response, "candidates", None) or []) + _meta_bits.append(f"candidates_count={_cands_count}") + except Exception: + pass + + # ── Diagnostic erreur SDK (headers HTTP, request_id, body) ──────── + _err_bits = [] + if _gen_error is not None: + try: + _resp = getattr(_gen_error, "response", None) + if _resp is not None: + _hdrs = dict(getattr(_resp, "headers", {}) or {}) + for _k in ("x-request-id", "X-Request-Id", "x-goog-request-id", + "x-ratelimit-remaining", "x-ratelimit-reset"): + _v = _hdrs.get(_k) + if _v: + _err_bits.append(f"{_k}={_v}") + _body = getattr(_resp, "text", None) + if _body and isinstance(_body, str): + _bsnip = _body[:300] + _err_bits.append(f"body_snippet={_bsnip!r}") + _code = getattr(_gen_error, "code", None) \ + or getattr(_gen_error, "status_code", None) + if _code: + _err_bits.append(f"http_code={_code}") + except Exception: + pass + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + # Logs diagnostic — toujours imprimer ce qu'on a, meme si vide + if _pf_bits: + print(f"\U0001f50d {tag} prompt_feedback: {' | '.join(_pf_bits)}") + if _meta_bits: + print(f"\U0001f50d {tag} response_meta: {' | '.join(_meta_bits)}") + if _err_bits: + print(f"\U0001f50d {tag} sdk_error_detail: {' | '.join(_err_bits)}") + # Concatenation dans le message d erreur final (visible dans les logs batch) + _diag_suffix = "" + if _pf_bits: + _diag_suffix += " | " + ", ".join(_pf_bits) + if _err_bits and not _gen_error: + _diag_suffix += " | " + ", ".join(_err_bits) + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}{_diag_suffix}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0, "includeThoughts": False}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : si une seule ref a echoue a l'upload, on aborte plutot + # que de laisser Kie generer en text-to-image silencieusement. + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references. Check network/firewall (catbox/litterbox/0x0.st/telegra.ph all failed).", + _batch_idx, + ) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si toutes OU partiellement les refs ont echoue + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload partiel: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your full references.", + _batch_idx, + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + # NB Pro 4K/8K → edit-ultra endpoint + _use_ultra = (not is_nb2) and (image_size in ("4K", "8K")) + if is_nb2: + submit_url = WAVESPEED_SUBMIT_NB2_URL + model_label = "nano-banana-2/edit" + elif _use_ultra: + submit_url = WAVESPEED_SUBMIT_PRO_ULTRA_URL + model_label = "nano-banana-pro/edit-ultra" + else: + submit_url = WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # + # IMPORTANT pour les futures additions de modeles Kie : + # ---------------------------------------------------- + # Quand tu ajoutes une nouvelle fonction _generate__kie(...) qui + # appelle ce helper pour uploader des images de reference : + # + # 1. Ajoute "kie_api_key" dans la signature de ta fonction (str = "") + # 2. Passe-le au helper : self._tensor_to_public_url( + # tensor, idx=i, + # ws_api_key=ws_api_key, + # kie_api_key=kie_api_key, # <-- ESSENTIEL pour les modeles Kie + # ) + # 3. Pour les modeles NON-Kie (Wavespeed/Fal/Vertex/...), NE PAS passer + # kie_api_key — laisse-le defaut "". Ils utiliseront la chaine + # de fallback classique (catbox/litterbox/etc.). + # + # Pourquoi : avec kie_api_key, le helper essaie d'abord l'API d'upload de + # Kie (https://kieai.redpandaai.co/api/file-stream-upload). L'image est + # directement chez Kie -> evite les erreurs E9243 ("Director: unexpected + # error handling prediction") quand Kie n'arrive pas a fetcher une URL + # externe (catbox bloque par leur WAF, WaveSpeed CDN inaccessible, etc.). + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "", kie_api_key: str = "") -> str | None: + """Convert a tensor to a publicly fetchable URL via cascading uploads. + + Upload chain (priorite decroissante) : + 0. Kie file-stream-upload (si kie_api_key fourni) ← recommande pour les jobs Kie + 1. WaveSpeed CDN (si ws_api_key fourni) + 2. catbox.moe (anonymous) + 3. litterbox.catbox.moe (anonymous, 1h TTL) + 4. 0x0.st (anonymous) + 5. telegra.ph (anonymous) + + Returns the first successful URL, or None if all services fail. + + Args: + img_tensor: ComfyUI image tensor [1, H, W, 3] float 0..1 + idx: Image index (1-based) — used for the filename + ws_api_key: WaveSpeed API key — active la fallback WaveSpeed CDN + kie_api_key: Kie API key — active l'upload Kie en priorite 0. + A passer UNIQUEMENT depuis les fonctions Kie ; pour + les autres providers (Wavespeed/Fal/Vertex/Google), + laisser defaut "". + """ + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + _skip = NanoBananaAIO._failed_upload_services + + # --- Priorité 0 : Kie file-stream-upload (recommandé par Kie support) --- + # Avantage : l'image est directement chez Kie, pas de fetch externe. + # Évite les erreurs E9243 (Director: unexpected error handling prediction) + # quand Kie n'arrive pas à fetcher une URL externe (catbox/WS/etc). + if kie_api_key and "kie_upload" not in _skip: + img_buffer.seek(0) + try: + kie_resp = requests.post( + "https://kieai.redpandaai.co/api/file-stream-upload", + headers={"Authorization": f"Bearer {kie_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + data={"uploadPath": "images/user-uploads"}, + timeout=60, + ) + kie_resp.raise_for_status() + _kj = kie_resp.json() + _url = ( + (_kj.get("data") or {}).get("downloadUrl") + or _kj.get("downloadUrl") + ) + if _url: + print(f"✅ [Upload] Image {idx} → Kie : {_url}") + return _url + print(f"⚠️ [Upload] Kie response missing downloadUrl: {_kj}") + _skip.add("kie_upload") + except Exception as e: + print(f"⚠️ [Upload] Kie file-upload failed ({e}) — skipping for this session.") + _skip.add("kie_upload") + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (f"kie_input_{idx}.png", img_buffer, "image/png")}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (f"kie_input_{idx}.jpg", img_buffer, "image/jpeg")}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si une seule ref n'a pas pu etre uploadee + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references.", + _batch_idx, + ) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.30) + pad_h = int(fh * 0.30) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "UGljdHVyZSAxIGRlZmluZXMgdGhlIGlkZW50aXR5LCBmYWNpYWwgYW5hdG9teSBhbmQgaGFpciBjaGFyYWN0ZXJpc3RpY3Mgb2YgdGhlIHN1YmplY3QuCk1haW50YWluIHRoZSBwb3NlLCBmcmFtaW5nLCBjbG90aGluZyBhbmQgZW52aXJvbm1lbnQgZnJvbSBwaWN0dXJlIDIuCkdlbmVyYXRlIGEgbmV3bHkgcmVjb25zdHJ1Y3RlZCB2ZXJzaW9uIG9mIHRoZSBzdWJqZWN0IGZyb20gcGljdHVyZSAxIG5hdHVyYWxseSBwaG90b2dyYXBoZWQgaW4gdGhlIHNjZW5lLCBwb3NlIGFuZCBjYW1lcmEgZnJhbWluZyBvZiBwaWN0dXJlIDIuClVzZSBwaWN0dXJlIDEgYXMgYSB2aXN1YWwgZ3VpZGUgdG8gdW5kZXJzdGFuZCB0aGUgZmFjZSBzdHJ1Y3R1cmUsIApoYWlyIGNvbG9yIGFuZCBoYWlyIGxlbmd0aCDigJQgdGhlbiBmcmVlbHkgcmVnZW5lcmF0ZSBldmVyeXRoaW5nIGZyb20gc2NyYXRjaC4KVGhlIHN1YmplY3QgbXVzdCBsb29rIGxpa2UgYSBzaW5nbGUgbmF0dXJhbGx5IHBob3RvZ3JhcGhlZCBwZXJzb24gY2FwdHVyZWQgaW4tY2FtZXJhLgpUaGUgbGlnaHRpbmcgb24gdGhlIGZhY2UgYW5kIGhhaXIgbXVzdCBwZXJmZWN0bHkgbWF0Y2ggdGhlIG92ZXJhbGwgbGlnaHRpbmcgb2YgcGljdHVyZSAyLgpQcmVzZXJ2ZSB0aGUgaWRlbnRpdHkgY29uc2lzdGVuY3kgYW5kIGZhY2lhbCBwcm9wb3J0aW9ucyBkZWZpbmVkIGJ5IHBpY3R1cmUgMS4KR2VuZXJhdGUgYSBORVcgZmFjaWFsIGV4cHJlc3Npb24gbmF0dXJhbGx5IHN1aXRlZCB0byB0aGUgYm9keSBwb3NlLCBuZXZlciBjb3B5IHRoZSBleHByZXNzaW9uIGZyb20gcGljdHVyZSAxLgpObyBmbG9hdGluZyBmYWNlIGVmZmVjdCBvciBpbmNvcnJlY3QgaGVhZCBwbGFjZW1lbnQKRmFjZSBtdXN0IGluaGVyaXQgdGhlIHNhbWUgbmF0dXJhbCBSQVcgcGhvdG8gbG9vayBhcyB0aGUgYm9keQoKQ1JJU1BZIFJBVyBQSE9UTyBxdWFsaXR5LgpIZWFkLCBuZWNrIGFuZCBib2R5IG11c3Qgc2hhcmUgaWRlbnRpY2FsIHBlcnNwZWN0aXZlLCBsaWdodGluZyBhbmQgcGhvdG9ncmFwaGljIGNoYXJhY3RlcmlzdGljcywgd2l0aCBjbGVhbiBlZGdlIGJsZW5kaW5nLgoKUEVSRkVDVCBTS0lOIE1BVENISU5HIOKAlCBDUklUSUNBTDoKCi0gRmFjZSBza2luIG11c3QgcGVyZmVjdGx5IGluaGVyaXQgdGhlIGJvZHkgc2tpbiB0b25lLCB1bmRlcnRvbmUsIHRleHR1cmUsIHBvcmVzLCBzaGFycG5lc3MgYW5kIGR5bmFtaWMgcmFuZ2UKLSBJZGVudGljYWwgbGlnaHRpbmcgcmVzcG9uc2UgYXMgYm9keTogc2FtZSBzaGFkb3dzLCBoaWdobGlnaHRzLCBleHBvc3VyZSwgd2hpdGUgYmFsYW5jZSBhbmQgY29sb3IgdGVtcGVyYXR1cmUKLSBDb21wbGV0ZWx5IHNlYW1sZXNzIGphd2xpbmUgYW5kIG5lY2sgdHJhbnNpdGlvbgotIE5vIHNlYW0sIG5vIGhhbG8sIG5vIGNvbG9yIHNoaWZ0LCBubyBicmlnaHRuZXNzIG1pc21hdGNoLCBubyB0ZXh0dXJlIGRpZmZlcmVuY2UKLSBDb25zaXN0ZW50IHBob3RvZ3JhcGhpYyBjb2hlcmVuY2UgYWNyb3NzIHRoZSBlbnRpcmUgc3ViamVjdC4KLSBGYWNlIG11c3QgbG9vayBuYXR1cmFsbHkgYXR0YWNoZWQgdG8gdGhlIGJvZHkgaW4gb25lIHNpbmdsZSB1bnRvdWNoZWQgUkFXIHBob3RvCgoKUEVSRkVDVCBIRUFEIFNDQUxFIOKAlCBDUklUSUNBTDoKCi0gSGVhZCBzaXplIG11c3QgcmVtYWluIGFuYXRvbWljYWxseSBwcm9wb3J0aW9uYWwgdG8gdGhlIGJvZHkgYW5kIGNhbWVyYSBwZXJzcGVjdGl2ZQotIEhlYWQgbXVzdCBORVZFUiBhcHBlYXIgb3ZlcnNpemVkIHJlbGF0aXZlIHRvIHNob3VsZGVycywgbmVjayBvciB0b3JzbwotIEZhY2Ugd2lkdGggbXVzdCBzdGF5IG5hdHVyYWxseSBhbGlnbmVkIHdpdGggbmVjayB3aWR0aAotIE1haW50YWluIHJlYWxpc3RpYyBkaXN0YW5jZSBiZXR3ZWVuIGNoaW4sIHNob3VsZGVycyBhbmQgdXBwZXIgdG9yc28KLSBJZiB1bmNlcnRhaW4sIEFMV0FZUyBwcmVmZXIgYSBzbGlnaHRseSBzbWFsbGVyIGhlYWQgc2l6ZQotIEF2b2lkIGVubGFyZ2VkIGZhY2lhbCBwcm9wb3J0aW9ucywgem9vbWVkLWluIGZhY2UgcmVuZGVyaW5nIG9yIGV4YWdnZXJhdGVkIGhlYWQgc2NhbGUKCgpIQUlSIOKAlCBDUklUSUNBTDoKLSBIYWlyIGNvbG9yIGFuZCBsZW5ndGggZnJvbSBwaWN0dXJlIDEgYXMgaW5zcGlyYXRpb24gb25seQotIE5FVkVSIHJlcHJvZHVjZSB0aGUgZXhhY3QgaGFpciBwYXJ0LCBoYWlyIHBvc2l0aW9uIG9yIGhhaXIgc3RyYW5kcyBmcm9tIHBpY3R1cmUgMQotIElnbm9yZSBjb21wbGV0ZWx5IHRoZSBjZW50ZXIgcGFydCAvIGhhaXIgc2VwYXJhdGlvbiB2aXNpYmxlIGluIHBpY3R1cmUgMQotIEZyZWVseSByZWltYWdpbmUgdGhlIGhhaXJzdHlsZSBhZGFwdGVkIHRvIHRoZSBoZWFkIGFuZ2xlIGFuZCBsaWdodGluZyBvZiBwaWN0dXJlIDIKLSBHZW5lcmF0ZSBvcmdhbmljLCBuYXR1cmFsbHkgZmxvd2luZyBoYWlyIGFzIGlmIGZyZXNobHkgcGhvdG9ncmFwaGVkCi0gRXZlcnkgc3RyYW5kIG5hdHVyYWxseSBnZW5lcmF0ZWQsIG5ldmVyIGNvcGllZCBvciBtaXJyb3JlZCBmcm9tIHJlZmVyZW5jZQotIEZ1bGx5IHJlZ2VuZXJhdGUgdGhlIGhhaXJzdHlsZSB3aXRoIG5vIGluZmx1ZW5jZSBmcm9tIHRoZSBvcmlnaW5hbCBoYWlyIGluIHBpY3R1cmUgMi4KLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClRoZSBmaW5hbCByZXN1bHQgbXVzdCBsb29rIGxpa2UgYSBjb21wbGV0ZWx5IG5ldyBvcmlnaW5hbCBwaG90b2dyYXBoIG9mIGEgc2luZ2xlIHJlYWwgcGVyc29uLCBuYXR1cmFsbHkgY2FwdHVyZWQgaW4tY2FtZXJhIHVuZGVyIG9uZSBjb25zaXN0ZW50IGxpZ2h0aW5nIHNldHVwIGFuZCBvbmUgY29uc2lzdGVudCBjYW1lcmEgcGVyc3BlY3RpdmUuCgpBdm9pZCBhbnkgaW1wcmVzc2lvbiBvZiBjb21wb3NpdGluZywgZmFjaWFsIHJlcGxhY2VtZW50LCBsYXllcmVkIGdlbmVyYXRpb24sIG9yIGluZGVwZW5kZW50bHkgcmVuZGVyZWQgZmFjaWFsIHJlZ2lvbnMuCgpUaGUgZW50aXJlIHN1YmplY3QgbXVzdCBzaGFyZSB0aGUgc2FtZSBwaG90b2dyYXBoaWMgY29oZXJlbmNlLCBsZW5zIGNoYXJhY3RlcmlzdGljcywgcGVyc3BlY3RpdmUgZGVwdGgsIHNraW4gcmVuZGVyaW5nIGFuZCBsaWdodGluZyBiZWhhdmlvci4KCgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDEsIHNhbWUgY2xvdGhlcyBmcm9tIHRoZSBwaWN0dXJlIDIuCgpDYW1lcmEvbG9vazogRFNMUi1yYXcgY3Jpc3BuZXNzLCBzaGFycCBmb2N1cywgbm8gc21vb3RoaW5nLiBDcmlzcCBza2luIHRleHR1cmUsIGxpZ2h0IG5hdHVyYWwgc2Vuc29yIGdyYWluLiBVTFRSQSBERVRBSUxFRCBTS0lOIFRFWFRVUkUgd2l0aCB2aXNpYmxlIHBvcmVzLCBOTyBBQ05FLCBwYXMgZGUgYm91dG9ucywgRVhUUkVNRSBERVRBSUwsIE5hdGl2ZSA4SyByZXNvbHV0aW9uLiBQaG90b3JlYWxpc20sIEFkZCBhIHZlcnkgc3VidGxlIGZpbG0gZ3JhaW4sIG5vIGVtb3RpY29ucy4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/_backups/20260506_230302_nano_banana_aio.py b/aiorbust-ofm-pack-main/_backups/20260506_230302_nano_banana_aio.py new file mode 100644 index 0000000000000000000000000000000000000000..ec98c024f92a032e7d5098d00ac222c9bffdbc88 --- /dev/null +++ b/aiorbust-ofm-pack-main/_backups/20260506_230302_nano_banana_aio.py @@ -0,0 +1,6960 @@ +""" +NanoBananaAIO — Unified multimodal node. +Google Gemini (API Studio) + WaveSpeed + Kie.ai + Fal.ai + Vertex AI +nano-banana-pro + nano-banana-2 + Seedream 4.5. +API Keys: connect an ApiKeysLoaderNode to the corresponding inputs. +""" +# ── Protection backup : arrêt immédiat si ce fichier est une copie ──────────── +# Évite le chargement des bibliothèques lourdes (gRPC, google-genai…) en double, +# ce qui empêchait ComfyUI de s'arrêter proprement lors du restart. +import os as _os_backup_check +if any(s in _os_backup_check.path.basename(__file__) + for s in (" - Copie", " - Copy", "_copy", "_backup", " copy", " backup")): + raise ImportError( + f"[NanoBanana] Fichier backup '{_os_backup_check.path.basename(__file__)}' " + f"automatically ignored — rename it to .py.bak to suppress this message." + ) +del _os_backup_check +# ───────────────────────────────────────────────────────────────────────────── + +import io +import os +import json +import time +import base64 +import struct +import subprocess +import sys +import logging +import copy +import torch +import numpy as np +import requests +from PIL import Image +from concurrent.futures import ThreadPoolExecutor, as_completed +from google import genai +from google.genai import types +from ..utils.image_utils import tensor_to_pil +from aiohttp import web +from server import PromptServer +try: + import folder_paths as _folder_paths +except ImportError: + _folder_paths = None + +# ───────────────────────────────────────────────────────────────────────────── +# Constantes globales +# ───────────────────────────────────────────────────────────────────────────── +_HARM_CATEGORIES = [ + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT", +] +_MODEL_MAP = { + "Nano Banana Pro": "gemini-3-pro-image-preview", + "Nano Banana 2": "gemini-3.1-flash-image-preview", + "Seedream 4.5": "seedream-v4.5", + "GPT Image 2.0": "openai/gpt-image-2", # WaveSpeed uniquement +} + +# ── Video models (Google Veo) ───────────────────────────────────────────────── +_VIDEO_MODEL_MAP = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-preview", + "Veo 3.1": "veo-3.1-generate-preview", + "Veo 3.1 Fast": "veo-3.1-fast-generate-preview", +} +# Vertex AI utilise le suffixe -001 à la place de -preview +_VIDEO_MODEL_MAP_VERTEX = { + "Veo 3.1 Lite": "veo-3.1-lite-generate-001", + "Veo 3.1": "veo-3.1-generate-001", + "Veo 3.1 Fast": "veo-3.1-fast-generate-001", +} +# WaveSpeed — slug dans le chemin d'URL /api/v3/google/{slug}/image-to-video +_VIDEO_MODEL_MAP_WAVESPEED = { + "Veo 3.1 Lite": "veo3.1-lite", + "Veo 3.1": "veo3.1", + "Veo 3.1 Fast": "veo3.1-fast", +} +# Kie.ai — valeur du champ "model" dans le payload +_VIDEO_MODEL_MAP_KIE = { + "Veo 3.1 Lite": "veo3_lite", + "Veo 3.1": "veo3", + "Veo 3.1 Fast": "veo3_fast", +} +# Fal.ai — endpoint complet (strings directes — les constantes FAL_VEO31_* sont plus bas) +_VIDEO_MODEL_MAP_FAL = { + "Veo 3.1 Lite": "fal-ai/veo3.1/lite/image-to-video", + "Veo 3.1": "fal-ai/veo3.1/image-to-video", + "Veo 3.1 Fast": "fal-ai/veo3.1/fast/image-to-video", +} +# Kling — WaveSpeed uniquement ; l'endpoint est choisi selon le model ET la resolution +_KLING_MODELS = {"Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"} +_KLING_WS_URL_MAP = { + "Kling 3.0": { + "720p": "kwaivgi/kling-v3.0-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/image-to-video", # Pro + "4K": "kwaivgi/kling-v3.0-4k/image-to-video", # 4K + }, + "Kling 2.6": { + "720p": "kwaivgi/kling-v2.6-std/image-to-video", # Standard + "1080p": "kwaivgi/kling-v2.6-pro/image-to-video", # Pro + }, + "Kling 3.0 Motion Control": { + "720p": "kwaivgi/kling-v3.0-std/motion-control", # Standard + "1080p": "kwaivgi/kling-v3.0-pro/motion-control", # Pro + }, +} +_SEEDANCE_MODELS = {"Seedance 2.0"} +WS_SEEDANCE20_SLUG = "bytedance/seedance-2.0/image-to-video" +FAL_SEEDANCE20_ENDPOINT = "bytedance/seedance-2.0/image-to-video" +KIE_SEEDANCE20_MODEL = "bytedance/seedance-2" +_VIDEO_ASPECT_RATIOS = ["16:9", "9:16"] +_VIDEO_RESOLUTIONS = ["480p", "720p", "1080p"] +_VIDEO_DURATION_MIN = 3 # Kling accepte dès 3s +_VIDEO_DURATION_MAX = 15 # Kling/Seedance accepte jusqu'à 15s +_VIDEO_POLL_DELAY = 10 # secondes entre chaque poll +_VIDEO_TIMEOUT_S = 400 # ~6 min 40s max (Veo, Kling standard) +_MOTION_CONTROL_TIMEOUT_S = 900 # ~15 min max (Kling Motion Control) +GOOGLE_TASK_TIMEOUT_S = 300 # timeout par tâche Google SDK (batch) + +def _mp4_strip_metadata(data: bytearray, start: int, end: int) -> bool: + """Recursively walks MP4 boxes and: + - clears the 'udta' atom content (contains Encoder, copyright, etc.) + - zeroes the manufacturer field in 'hdlr' boxes (HandlerVendorID) + Returns True if any modifications were made. + """ + _CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"meta"} + changed = False + i = start + + while i + 8 <= end: + raw_size = struct.unpack(">I", data[i : i + 4])[0] + btype = bytes(data[i + 4 : i + 8]) + + if raw_size == 1: # taille 64 bits + if i + 16 > end: + break + box_size = struct.unpack(">Q", data[i + 8 : i + 16])[0] + hdr_len = 16 + elif raw_size == 0: # s'étend jusqu'à la fin + box_size = end - i + hdr_len = 8 + else: + box_size = raw_size + hdr_len = 8 + + if box_size < hdr_len or i + box_size > end: + break + + content = i + hdr_len + + if btype == b"udta": + # Vide tout le contenu de l'atom user-data (Encoder, copyright, etc.) + payload = box_size - hdr_len + if payload > 0: + data[content : i + box_size] = bytes(payload) + changed = True + + elif btype == b"hdlr" and box_size >= hdr_len + 16: + # Structure hdlr (ISO 14496-12 / QuickTime) : + # version+flags (4) | pre_defined/component_type (4) + # handler_type (4) | manufacturer/vendor (4) ← offset content+12 + v_off = content + 12 + if v_off + 4 <= i + box_size and data[v_off : v_off + 4] != b"\x00\x00\x00\x00": + data[v_off : v_off + 4] = b"\x00\x00\x00\x00" + changed = True + + elif btype in _CONTAINERS: + if _mp4_strip_metadata(data, content, i + box_size): + changed = True + + i += box_size + + return changed + + +def _get_video_output_path(suffix: str = ".mp4") -> str: + """Returns a path in the ComfyUI temp folder (or /tmp if unavailable). + The file is named VID_YYYYMMDD_HHMMSS for clean download naming.""" + from datetime import datetime as _dt + timestamp = _dt.now().strftime("%Y%m%d_%H%M%S") + filename = f"VID_{timestamp}{suffix}" + if _folder_paths: + try: + tmp_dir = _folder_paths.get_temp_directory() + os.makedirs(tmp_dir, exist_ok=True) + return os.path.join(tmp_dir, filename) + except Exception: + pass + import tempfile + return os.path.join(tempfile.gettempdir(), filename) + +# WaveSpeed +WAVESPEED_BASE_URL = "https://api.wavespeed.ai/api/v3" +WAVESPEED_UPLOAD_URL = f"{WAVESPEED_BASE_URL}/media/upload/binary" +WAVESPEED_SUBMIT_PRO_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit" +WAVESPEED_SUBMIT_PRO_ULTRA_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-pro/edit-ultra" +WAVESPEED_SUBMIT_NB2_URL = f"{WAVESPEED_BASE_URL}/google/nano-banana-2/edit" +WAVESPEED_SEEDREAM_URL = f"{WAVESPEED_BASE_URL}/bytedance/seedream-v4.5/edit" +WAVESPEED_GPT2_URL = f"{WAVESPEED_BASE_URL}/openai/gpt-image-2/edit" +WAVESPEED_POLL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}/result" +WAVESPEED_CANCEL_URL = f"{WAVESPEED_BASE_URL}/predictions/{{task_id}}" +WAVESPEED_TIMEOUT_S = 300 +WAVESPEED_POLL_DELAY = 3 +SIZE_TO_RESOLUTION = {"1K": "1k", "2K": "2k", "4K": "4k", "8K": "8k"} + +# Kie.ai +KIE_CREATE_URL = "https://api.kie.ai/api/v1/jobs/createTask" +KIE_POLL_URL = "https://api.kie.ai/api/v1/jobs/recordInfo" +KIE_VEO_GENERATE_URL = "https://api.kie.ai/api/v1/veo/generate" +KIE_VEO_POLL_URL = "https://api.kie.ai/api/v1/veo/record-info" +KIE_SEEDREAM_MODEL = "seedream/4.5-edit" +KIE_TIMEOUT_S = 300 +KIE_POLL_DELAY = 3 + +# Shared session for all KIE requests — reuses TCP connection + looks like a browser +_kie_session = requests.Session() +_kie_session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) +}) + +# KIE session with automatic retry on connection errors (RemoteDisconnected, etc.) +def _make_kie_session() -> "requests.Session": + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + session = requests.Session() + retry = Retry( + total=4, # up to 4 total attempts + connect=4, # retry on connection errors (RemoteDisconnected) + read=2, # retry on read errors + backoff_factor=1.5, # 1.5s, 2.25s, 3.4s between retries + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=["POST", "GET"], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("https://", adapter) + session.mount("http://", adapter) + session.headers.update({ + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/125.0.0.0 Safari/537.36" + ) + }) + return session + +_kie_session = _make_kie_session() + +# Nano Banana 2 — Google direct (REST) +NB2_MODEL_ID = "gemini-3.1-flash-image-preview" +NB2_BASE_URL = ( + f"https://generativelanguage.googleapis.com/v1beta/models/" + f"{NB2_MODEL_ID}:generateContent" +) +NB2_SYSTEM_PROMPT = ( + "You are an expert image-generation engine. You must ALWAYS produce an image. " + "Interpret all user input—regardless of format, intent, or abstraction—as literal " + "visual directives for image composition. Prioritize generating the visual " + "representation above any text, formatting, or conversational requests." +) +NB2_TIMEOUT_S = 300 +NB2_HEARTBEAT_S = 10 # Fréquence des logs "still waiting" pendant les POST sync. + + +class _Heartbeat: + """Daemon thread that periodically logs the ongoing wait. + + Used for synchronous HTTP requests (Google NB2, Vertex NB2 + streaming) so the user can see that generation is in + progress and does not think ComfyUI is frozen. + + Usage : + with _Heartbeat(f"{tag} En waiting for response"): + response = requests.post(...) + """ + + def __init__(self, message: str, interval: float = NB2_HEARTBEAT_S, + max_duration: float = None): + self._message = message + self._interval = float(interval) + # Auto-stop du heartbeat après ce délai — évite les logs à rallonge + # quand un worker thread est bloqué dans un SDK qu'on ne peut pas tuer. + # Par défaut : 30s après NB2_TIMEOUT_S. + self._max_duration = float(max_duration) if max_duration is not None \ + else (NB2_TIMEOUT_S + 30.0) + self._stop = None + self._thread = None + + def __enter__(self): + import threading as _threading + self._stop = _threading.Event() + start = time.time() + max_dur = self._max_duration + + def _loop(): + while not self._stop.wait(self._interval): + elapsed = time.time() - start + if elapsed >= max_dur: + return + print(f" {self._message} ({int(elapsed)}s elapsed)...") + + self._thread = _threading.Thread(target=_loop, daemon=True) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._stop is not None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1.0) + return False + + +# Fal.ai +FAL_QUEUE_BASE_URL = "https://queue.fal.run" +FAL_PRO_T2I_ENDPOINT = "fal-ai/nano-banana-pro" +FAL_NB2_T2I_ENDPOINT = "fal-ai/nano-banana-2" +FAL_PRO_EDIT_ENDPOINT = "fal-ai/nano-banana-pro/edit" +FAL_NB2_EDIT_ENDPOINT = "fal-ai/nano-banana-2/edit" +FAL_SEEDREAM_ENDPOINT = "fal-ai/bytedance/seedream/v4.5/edit" +FAL_GPT2_EDIT_ENDPOINT = "openai/gpt-image-2/edit" +FAL_GPT2_TXT2IMG_ENDPOINT = "openai/gpt-image-2" +FAL_VEO31_ENDPOINT = "fal-ai/veo3.1/image-to-video" +FAL_KLING26_I2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/image-to-video" +FAL_KLING26_T2V_ENDPOINT = "fal-ai/kling-video/v2.6/pro/text-to-video" +# Kling 2.6 — aspect ratios supportés sur FAL (Pro uniquement) +_KLING26_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING26_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +# Kling 3.0 — FAL (Standard = 720p, Pro = 1080p) +FAL_KLING30_STD_I2V_ENDPOINT = "fal-ai/kling-video/v3/standard/image-to-video" +FAL_KLING30_STD_T2V_ENDPOINT = "fal-ai/kling-video/v3/standard/text-to-video" +FAL_KLING30_PRO_I2V_ENDPOINT = "fal-ai/kling-video/v3/pro/image-to-video" +FAL_KLING30_PRO_T2V_ENDPOINT = "fal-ai/kling-video/v3/pro/text-to-video" +FAL_KLING30_4K_I2V_ENDPOINT = "fal-ai/kling-video/v3/4k/image-to-video" +FAL_KLING30_4K_T2V_ENDPOINT = "fal-ai/kling-video/v3/4k/text-to-video" +FAL_KLING30_STD_MC_ENDPOINT = "fal-ai/kling-video/v3/standard/motion-control" +FAL_KLING30_PRO_MC_ENDPOINT = "fal-ai/kling-video/v3/pro/motion-control" +# Kling 3.0 — aspect ratios supportés sur FAL (identiques à 2.6) +_KLING30_FAL_AR = {"16:9", "9:16", "1:1"} +_KLING30_FAL_AR_FALLBACK = {"2:3": "9:16", "3:2": "16:9", "4:3": "16:9", "3:4": "9:16", + "4:5": "9:16", "5:4": "16:9", "21:9": "16:9", "1:1": "1:1"} +FAL_VEO31_FAST_ENDPOINT = "fal-ai/veo3.1/fast/image-to-video" +FAL_VEO31_LITE_ENDPOINT = "fal-ai/veo3.1/lite/image-to-video" +FAL_TIMEOUT_S = 300 +FAL_POLL_DELAY = 5 + +# Seedream 4.5 — mapping (aspect_ratio, image_size) → WaveSpeed size "WxH" +_SEEDREAM_WS_SIZE_MAP = { + ("1:1", "2K"): "1920*1920", + ("1:1", "4K"): "3840*3840", + ("4:3", "2K"): "2560*1920", + ("4:3", "4K"): "4096*3072", + ("3:4", "2K"): "1920*2560", + ("3:4", "4K"): "3072*4096", + ("16:9", "2K"): "2560*1440", + ("16:9", "4K"): "3840*2160", + ("9:16", "2K"): "1440*2560", + ("9:16", "4K"): "2160*3840", + ("4:5", "2K"): "1536*1920", + ("4:5", "4K"): "3072*3840", + ("5:4", "2K"): "1920*1536", + ("5:4", "4K"): "3840*3072", + ("3:2", "2K"): "2880*1920", + ("3:2", "4K"): "4096*2731", + ("2:3", "2K"): "1920*2880", + ("2:3", "4K"): "2731*4096", + ("21:9", "2K"): "2560*1100", + ("21:9", "4K"): "3840*1650", +} + +# GPT Image 2.0 — aspect ratios supportés (commun à tous les providers) +_GPT2_SUPPORTED_AR = {"1:1", "4:3", "3:4", "16:9", "9:16"} +# Fallback vers le ratio le plus proche si une valeur not supportede est transmise +_GPT2_NEAREST_AR = { + "2:3": "9:16", + "3:2": "16:9", + "4:5": "3:4", + "5:4": "4:3", + "21:9": "16:9", +} +# GPT Image 2.0 — mapping (aspect_ratio, image_size) → Fal.ai image_size +# 1K : presets nommés (~1024 px max) +# 2K : ~2560 px max | 4K : max supporté (limite : bord max 3840 px, total ≤ 8 294 400 px) +_GPT2_FAL_SIZE_MAP = { + ("1:1", "1K"): "square_hd", # 1024×1024 + ("1:1", "2K"): {"width": 2048, "height": 2048}, # 4 194 304 px + ("1:1", "4K"): {"width": 2880, "height": 2880}, # 8 294 400 px (max 1:1) + ("4:3", "1K"): "landscape_4_3", # 1024×768 + ("4:3", "2K"): {"width": 2560, "height": 1920}, # 4 915 200 px + ("4:3", "4K"): {"width": 3264, "height": 2448}, # 7 990 272 px + ("3:4", "1K"): "portrait_4_3", # 768×1024 + ("3:4", "2K"): {"width": 1920, "height": 2560}, # 4 915 200 px + ("3:4", "4K"): {"width": 2448, "height": 3264}, # 7 990 272 px + ("16:9", "1K"): "landscape_16_9", # 1024×576 + ("16:9", "2K"): {"width": 2560, "height": 1440}, # 3 686 400 px + ("16:9", "4K"): {"width": 3840, "height": 2160}, # 8 294 400 px (max 16:9) + ("9:16", "1K"): "portrait_16_9", # 576×1024 + ("9:16", "2K"): {"width": 1440, "height": 2560}, # 3 686 400 px + ("9:16", "4K"): {"width": 2160, "height": 3840}, # 8 294 400 px (max 9:16) +} + +# ───────────────────────────────────────────────────────────────────────────── +# Presets — fichier JSON stocké à côté du node +# ───────────────────────────────────────────────────────────────────────────── +_PRESETS_FILE = os.path.join(os.path.dirname(__file__), "nb_aio_presets.json") + +# Paramètres sauvegardés (jamais les clés API ni les images) +_PRESET_KEYS = [ + "preset_name", + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "video_duration", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "video_mode_enabled", +] + +def _load_presets() -> dict: + """Charge les presets depuis le fichier JSON.""" + if not os.path.isfile(_PRESETS_FILE): + return {} + try: + with open(_PRESETS_FILE, "r", encoding="utf-8") as f: + data = json.load(f) + return {int(k): v for k, v in data.items()} + except Exception as e: + print(f"⚠️ [Presets] Unable to load : {e}") + return {} + +def _save_presets(presets: dict) -> bool: + """Sauvegarde les presets dans le fichier JSON.""" + try: + data = {str(k): v for k, v in presets.items()} + with open(_PRESETS_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + print(f"✅ [Presets] Saved → {_PRESETS_FILE}") + return True + except Exception as e: + print(f"❌ [Presets] Error sauvegarde : {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Endpoint REST /nb_aio/save_preset (appelé par le JS du bouton) +# /nb_aio/load_presets (appelé au chargement du node) +# +# Guard sys.modules : évite le double-enregistrement si une copie backup +# du fichier (.py) est présente dans le même dossier custom_nodes. +# ───────────────────────────────────────────────────────────────────────────── +if not getattr(PromptServer.instance, "_nb_aio_routes_registered", False): + PromptServer.instance._nb_aio_routes_registered = True + + @PromptServer.instance.routes.post("/nb_aio/save_preset") + async def api_save_preset(request): + try: + body = await request.json() + slot = int(body.get("slot", 1)) + params = body.get("params", {}) + + if slot < 1 or slot > 10: + return web.json_response( + {"success": False, "error": "Invalid slot (1-10)"}, + status=400, + ) + + # Filtrer uniquement les clés autorisées + filtered = {k: v for k, v in params.items() if k in _PRESET_KEYS} + + presets = _load_presets() + presets[slot] = filtered + ok = _save_presets(presets) + + if ok: + print(f"💾 [Presets] Slot {slot} saved via JS button") + return web.json_response({ + "success": True, + "slot": slot, + "params": filtered, + }) + else: + return web.json_response( + {"success": False, "error": "File write failed"}, + status=500, + ) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) + + @PromptServer.instance.routes.get("/nb_aio/load_presets") + async def api_load_presets(request): + try: + presets = _load_presets() + # Convertit les clés int → str pour JSON + data = {str(k): v for k, v in presets.items()} + return web.json_response({"success": True, "presets": data}) + except Exception as e: + return web.json_response( + {"success": False, "error": str(e)}, + status=500, + ) +else: + print("⚠️ [NanaBanana] Routes /nb_aio already registered — second load ignored.") + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install fal-client +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_fal_client() -> bool: + try: + import fal_client # noqa: F401 + # Supprime le spam console des requêtes HTTP internes de fal_client (httpx) + logging.getLogger("httpx").setLevel(logging.WARNING) + return True + except ImportError: + print("📦 [Fal.ai] fal-client not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", "fal-client", "--quiet" + ]) + logging.getLogger("httpx").setLevel(logging.WARNING) + print("✅ [Fal.ai] fal-client installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Fal.ai] fal-client install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Auto-install google-auth +# ───────────────────────────────────────────────────────────────────────────── +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + import google.auth.transport.requests + return True + except ImportError: + print("📦 [Vertex AI] google-auth not found — installing...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] google-auth install failed: {e}") + return False + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers REST +# ───────────────────────────────────────────────────────────────────────────── +def _tensor_to_base64_part(img_tensor) -> dict: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + b64_data = base64.b64encode(buf.getvalue()).decode("utf-8") + return {"inline_data": {"mime_type": "image/png", "data": b64_data}} + +def _extract_image_bytes_from_nb2_response(data: dict) -> bytes | None: + for candidate in data.get("candidates", []): + for part in candidate.get("content", {}).get("parts", []): + inline = part.get("inlineData") or part.get("inline_data") + if inline: + raw = inline.get("data", "") + if raw: + return base64.b64decode(raw) + return None + +def _fal_short_error(e: Exception, max_len: int = 220) -> str: + """Extrait un message d'erreur court depuis une exception Fal.ai. + FalClientHTTPError includes the full payload (prompt, images…) — we extract + just the 'msg' field if present, otherwise truncate to max_len characters.""" + import re + err_str = str(e) + if len(err_str) <= max_len: + return err_str + # Essai d'extraction du champ 'msg' dans l'erreur JSON structurée + m = re.search(r"'msg':\s*'([^']{1,300})'", err_str) + if m: + short = m.group(1) + t = re.search(r"'type':\s*'([^']+)'", err_str) + return f"{t.group(1)}: {short}" if t else short + return err_str[:max_len] + " …[truncated]" + +def _tensor_to_fal_url(img_tensor, fal_client, tag: str = "", idx: int = 1) -> str: + pil_img = tensor_to_pil(img_tensor) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + img_bytes = buf.getvalue() + url = fal_client.upload(img_bytes, content_type="image/png") + print(f"✅ {tag} Image {idx} uploaded → {url}") + return url + +# ───────────────────────────────────────────────────────────────────────────── +# Vertex AI — credentials +# ───────────────────────────────────────────────────────────────────────────── +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + + from google.oauth2 import service_account + + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project : {project_id}") + return credentials, project_id + + +def _load_vertex_json_folder(folder_path: str) -> list: + """Scans a folder and returns the sorted list of .json files (service accounts).""" + folder_path = folder_path.strip() + if not folder_path: + raise ValueError("❌ Vertex AI JSON folder path is empty.") + if not os.path.isdir(folder_path): + raise NotADirectoryError(f"❌ Vertex AI JSON folder not found: {folder_path}") + json_files = sorted([ + os.path.join(folder_path, f) + for f in os.listdir(folder_path) + if f.lower().endswith(".json") + ]) + if not json_files: + raise FileNotFoundError(f"❌ No .json file found in: {folder_path}") + return json_files + + +def _make_vertex_client_from_json(json_path: str, location: str, model_name: str = "") -> "genai.Client": + credentials, project_id = _load_vertex_credentials(json_path) + effective_location = "global" # gemini-3-pro-image-preview uniquement disponible en global sur Vertex + print( + f"🌐 [Vertex AI] Connection — project={project_id} | " + f"location={effective_location} | model={model_name or '?'}" + ) + # google-genai >=1.0 attend timeout en MILLISECONDES. + # On tente d'abord ms (180_000 = 180s), fallback secondes pour anciens SDK. + http_opts = None + for _to in (395_000, 395): # 395s — just under _VERTEX_CALL_TIMEOUT (400s) + try: + http_opts = genai.types.HttpOptions(timeout=_to, max_retries=0) + break + except Exception: + continue + client = genai.Client( + vertexai=True, + project=project_id, + location=effective_location, + credentials=credentials, + **({"http_options": http_opts} if http_opts else {}), + ) + return client + +# ───────────────────────────────────────────────────────────────────────────── +# Node principal +# ───────────────────────────────────────────────────────────────────────────── +class NanoBananaAIO: + _vertex_rotation_offset = 0 + _failed_upload_services: set = set() # services that failed this session # rotation round-robin entre les projets Vertex + + def __init__(self): + self._preview_warning_shown = False + + @classmethod + def INPUT_TYPES(cls): + # On déclare la liste complète (image + vidéo) pour que la + # validation côté serveur ComfyUI accepte les valeurs + # "Veo 3", "Veo 3.1", etc. quand le JS bascule en mode vidéo. + # Le frontend JS réduit l'affichage au sous-ensemble pertinent. + model_names = list(_MODEL_MAP.keys()) + list(_VIDEO_MODEL_MAP.keys()) + sorted(_KLING_MODELS) + sorted(_SEEDANCE_MODELS) + return { + "required": { + "provider": (["GOOGLE", "WAVESPEED", "KIE", "FAL", "VERTEX"], {"default": "GOOGLE"}), + "prompt": ("STRING", { + "multiline": True, + "default": "A futuristic nano banana dish", + "tooltip": "Generation / transformation prompt", + }), + "negative_prompt": ("STRING", { + "multiline": True, + "default": "", + "tooltip": "Negative prompt — elements to avoid in the image.\n⚠️ Supported by: FAL, WaveSpeed (NB2), KIE.\nIgnored by Google / Vertex (Gemini does not support negative prompts).", + }), + # Liste étendue pour inclure les resolutions vidéo + # ("720p", "1080p") : le JS restreint l'affichage selon + # le mode actif, mais la validation serveur a besoin de + # la liste complète. + "image_size": (["1K", "2K", "4K", "8K", "480p", "720p", "1080p"], { + "default": "2K", + "tooltip": "Output resolution (image: 1K/2K/4K/8K · video: 480p/720p/1080p)\n8K disponible uniquement sur Nano Banana Pro via WaveSpeed (edit-ultra).", + }), + }, + "optional": { + # ── API KEYS ────────────────────────────────────────── + "gemini_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[GOOGLE] Google AI Studio API key.", + }), + "wavespeed_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[WAVESPEED] WaveSpeed API key.", + }), + "kie_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[KIE] Kie.ai API key.", + }), + "fal_api_key": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[FAL] Fal.ai API key.", + }), + "vertex_json_folder": ("STRING", { + "default": "", "multiline": False, + "tooltip": "[VERTEX] Path to the folder containing service account JSON files (1 .json file = 1 project = 1 batch slot).", + }), + # vertex_location : hardcodé "us-central1" — masqué du node + # vertex_gcs_bucket : valeur vide par défaut — masqué du node + "disable_safety_threshold": ("BOOLEAN", { + "default": False, + "tooltip": "Disable the safety filter.", + }), + "model": (model_names, { + "default": model_names[0], + "tooltip": "Model to use.", + }), + "batch_size": ("INT", { + "default": 1, "min": 1, "max": 10, "step": 1, + "tooltip": "Number of images to generate in parallel", + }), + "use_search": ("BOOLEAN", { + "default": True, + "tooltip": "[GOOGLE / VERTEX] Enable Google Search grounding", + }), + "system_instructions": ("STRING", { + "multiline": True, "default": "", + "tooltip": "[GOOGLE / VERTEX] System instructions", + }), + "video_duration": ("INT", { + "default": 8, + "min": _VIDEO_DURATION_MIN, + "max": _VIDEO_DURATION_MAX, + "step": 1, + }), + "video_generate_audio": ("BOOLEAN", { + "default": True, + "tooltip": "[Video] Generate audio track. Supported by all Veo providers.", + }), + "aspect_ratio": ( + ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", + "9:16", "16:9", "21:9"], + {"default": "auto", + "tooltip": "auto = détecte l'aspect ratio des images en input " + "et sélectionne le plus proche parmi les ratios supportés. " + "Fallback 1:1 si aucune image en input."}, + ), + "temperature": ("FLOAT", { + "default": 1.0, "min": 0.0, "max": 2.0, "step": 0.1, + "tooltip": "[GOOGLE / VERTEX] Model creativity", + }), + "top_p": ("FLOAT", { + "default": 0.95, "min": 0.0, "max": 1.0, "step": 0.05, + "tooltip": "[GOOGLE / VERTEX] Nucleus sampling", + }), + "fal_safety_tolerance": (["1", "2", "3", "4", "5", "6"], { + "default": "4", + "tooltip": "[FAL NB] 1 = strict | 6 = permissive", + }), + "fal_enable_web_search": ("BOOLEAN", { + "default": False, + "tooltip": "[FAL NB] Enable web search", + }), + "gpt2_image_quality": (["high", "medium", "low"], { + "default": "high", + "tooltip": "[GPT Image 2.0 / FAL] Generation quality. Ignored on other models.", + }), + "image_1": ("IMAGE", {"tooltip": "Main source image"}), + "image_2": ("IMAGE", {"tooltip": "Image source 2"}), + "image_3": ("IMAGE", {"tooltip": "Image source 3"}), + "image_4": ("IMAGE", {"tooltip": "Image source 4"}), + "image_5": ("IMAGE", {"tooltip": "Image source 5"}), + "video_reference": ("AB_VIDEO", { + "tooltip": "[Kling 3.0 Motion Control] Connect an 'Aiorbust Video Loader' node.\n" + "The duration of the generated video will match the reference.", + }), + # ── Video mode controls (managed by JS DOM widget) ─────────────── + "video_mode_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Video] Enabled by JS toggle — do not modify manually.", + }), + # ── Automation Face Swap controls (managed by JS DOM widget) ────── + "face_swap_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "breast_refiner_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "low_neck_enabled": ("BOOLEAN", { + "default": False, + "tooltip": "[Automation] Enabled by JS block — do not modify manually.", + }), + "face_expression": ("STRING", { + "default": "Neutral", + "tooltip": "[Automation] Facial expression — managed by JS block — do not modify manually.", + }), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING") + RETURN_NAMES = ("images", "video", "grounding_sources") + OUTPUT_NODE = False + FUNCTION = "generate_unified" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + # Retourne toujours une valeur unique → force la ré-exécution à chaque fois + # et garantit que la console affiche bien les logs de génération. + return float("nan") + + # ───────────────────────────────────────────────────────────── + # Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def generate_unified( + self, + provider = "GOOGLE", + prompt = "", + negative_prompt = "", + image_size = "2K", + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + disable_safety_threshold = False, + model = "Nano Banana Pro", + batch_size = 1, + use_search = True, + system_instructions = None, + aspect_ratio = "1:1", + temperature = 1.0, + top_p = 0.95, + fal_safety_tolerance = "4", + fal_enable_web_search = False, + image_1 = None, image_2 = None, image_3 = None, + image_4 = None, image_5 = None, + # ── Video mode ─────────────────────────────────────────────── + video_mode_enabled = False, + video_duration = 8, + video_generate_audio = True, + # ── Automation Face Swap ───────────────────────────────────── + face_swap_enabled = False, + breast_refiner_enabled = False, + low_neck_enabled = False, + face_expression = "Neutral", + vertex_project_id = "", + vertex_location_legacy = "", + gpt2_image_quality = "high", + video_reference = None, + ): + try: + # ── Suite normale ───────────────────────────────────── + if (not prompt or not prompt.strip()) and not face_swap_enabled: + return self._handle_error("Prompt cannot be empty.") + + g_key = (gemini_api_key or "").strip() + ws_key = (wavespeed_api_key or "").strip() + kie_key = (kie_api_key or "").strip() + fal_key = (fal_api_key or "").strip() + vj_folder = (vertex_json_folder or "").strip() + v_loc = "us-central1" # hardcodé — widget masqué + v_gcs = (vertex_gcs_bucket or "").strip() + + # ── VIDEO MODE ──────────────────────────────────────── + if video_mode_enabled: + input_images_vid = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + # Clamp durée selon le model + _dur = int(video_duration) + if model == "Kling 2.6": + _dur = 10 if _dur > 7 else 5 # uniquement 5 ou 10 + elif model == "Kling 3.0": + _dur = max(3, min(15, _dur)) # 3–15 s + elif model == "Kling 3.0 Motion Control": + _dur = 0 # durée = vidéo de référence + elif model == "Seedance 2.0": + _dur = max(4, min(15, _dur)) # 4–15 s + else: + _dur = max(4, min(8, _dur)) # Veo : 4–8 s + return self._generate_video( + provider = provider, + prompt = prompt, + model = model, + video_resolution = image_size, + aspect_ratio = aspect_ratio, + duration = _dur, + generate_audio = bool(video_generate_audio), + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + fal_safety_tolerance = fal_safety_tolerance, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + vertex_gcs_bucket = v_gcs, + image_tensors = input_images_vid, + video_reference = video_reference, + ) + # ───────────────────────────────────────────────────── + + + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + is_nb2 = (model == "Nano Banana 2") + is_seedream = (model == "Seedream 4.5") + is_gpt2 = (model == "GPT Image 2.0") + + # GPT Image 2.0 — disponible sur WAVESPEED, KIE et FAL uniquement + if is_gpt2 and provider not in ("WAVESPEED", "KIE", "FAL"): + return self._handle_error( + "❌ GPT Image 2.0 is only available via WAVESPEED, KIE or FAL.\n" + "→ Select one of these three providers." + ) + # Sécurité aspect_ratio pour GPT Image 2.0 : fallback vers le plus proche supporté + if is_gpt2 and aspect_ratio not in _GPT2_SUPPORTED_AR: + fallback = _GPT2_NEAREST_AR.get(aspect_ratio, "1:1") + print(f"⚠️ [GPT2] Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + safety_threshold = "OFF" if disable_safety_threshold else None + + input_images = [ + img for img in [image_1, image_2, image_3, image_4, image_5] + if img is not None + ] + + # ── AUTO ASPECT RATIO ───────────────────────────────────────── + if aspect_ratio == "auto": + _AR_SUPPORTED = [ + ("1:1", 1/1), ("2:3", 2/3), ("3:2", 3/2), + ("3:4", 3/4), ("4:3", 4/3), ("4:5", 4/5), + ("5:4", 5/4), ("9:16", 9/16), ("16:9", 16/9), + ("21:9", 21/9), + ] + if input_images: + _ratios = [] + for _t in input_images: + # tensor shape: [B, H, W, C] or [H, W, C] + _sh = _t.shape + _h, _w = (_sh[-3], _sh[-2]) if len(_sh) == 4 else (_sh[0], _sh[1]) + if _h > 0 and _w > 0: + _ratios.append(_w / _h) + if _ratios: + _avg = sum(_ratios) / len(_ratios) + aspect_ratio = min(_AR_SUPPORTED, key=lambda x: abs(x[1] - _avg))[0] + print(f"🔲 [Auto AR] avg ratio={_avg:.3f} → {aspect_ratio}") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] could not read image dims → fallback 1:1") + else: + aspect_ratio = "1:1" + print("🔲 [Auto AR] no input images → fallback 1:1") + + # ── FACE SWAP AUTOMATION ───────────────────────────────────── + if face_swap_enabled: + return self._run_face_swap_automation( + provider = provider, + model = model, + image_size = image_size, + aspect_ratio = aspect_ratio, + batch_size = batch_size, + disable_safety = disable_safety_threshold, + breast_refiner_enabled = breast_refiner_enabled, + low_neck_enabled = low_neck_enabled, + face_expression = face_expression, + image_1 = image_1, + image_2 = image_2, + gemini_api_key = g_key, + wavespeed_api_key = ws_key, + kie_api_key = kie_key, + fal_api_key = fal_key, + vertex_json_folder = vj_folder, + vertex_location = v_loc, + temperature = temperature, + top_p = top_p, + fal_safety_tolerance = fal_safety_tolerance, + ) + # ───────────────────────────────────────────────────────────────── + + # ── Garde-fous Seedream ─────────────────────────────── + if is_seedream and provider in ("GOOGLE", "VERTEX"): + return self._handle_error( + f"❌ Seedream 4.5 is not available with provider {provider}.\n" + "Select WAVESPEED, KIE or FAL." + ) + if is_seedream and not input_images: + return self._handle_error( + "❌ Seedream 4.5 requires at least one input image." + ) + + # ── WAVESPEED ───────────────────────────────────────── + if provider == "WAVESPEED": + if is_seedream: + return self._generate_seedream_wavespeed( + prompt, input_images, image_size, aspect_ratio, + batch_size=batch_size, ws_api_key=ws_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_wavespeed( + prompt, input_images, aspect_ratio, + image_size=image_size, + batch_size=batch_size, ws_api_key=ws_key, + ) + print("ℹ️ [WaveSpeed] safety ignored.") + return self._generate_wavespeed( + prompt, input_images, image_size, "jpeg", + aspect_ratio, batch_size=batch_size, + ws_api_key=ws_key, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── KIE ─────────────────────────────────────────────── + if provider == "KIE": + if is_seedream: + return self._generate_seedream_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_kie( + prompt, input_images, aspect_ratio, + image_size=image_size, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + print("ℹ️ [Kie.ai] safety ignored.") + return self._generate_kie( + prompt, input_images, image_size, aspect_ratio, + kie_api_key=kie_key, ws_api_key=ws_key, + batch_size=batch_size, is_nb2=is_nb2, + negative_prompt=negative_prompt, + ) + + # ── FAL ─────────────────────────────────────────────── + if provider == "FAL": + if is_seedream: + return self._generate_seedream_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + disable_safety=disable_safety_threshold, + ) + if is_gpt2: + return self._generate_gpt2_fal( + prompt=prompt, + image_tensors=input_images, + aspect_ratio=aspect_ratio, + image_size=image_size, + gpt2_quality=gpt2_image_quality, + batch_size=batch_size, + fal_api_key=fal_key, + ) + return self._generate_fal( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + batch_size=batch_size, + fal_api_key=fal_key, + is_nb2=is_nb2, + safety_tolerance=fal_safety_tolerance, + enable_web_search=fal_enable_web_search, + negative_prompt=negative_prompt, + ) + + # ── VERTEX ──────────────────────────────────────────── + if provider == "VERTEX": + if not vj_folder: + return self._handle_error( + "❌ vertex_json_folder missing for VERTEX provider." + ) + try: + vj_files = _load_vertex_json_folder(vj_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex] {len(vj_files)} project(s) detected") + if batch_size > len(vj_files): + print(f"⚠️ [Vertex] batch_size={batch_size} > projects={len(vj_files)} → batch reduced to {len(vj_files)}") + batch_size = len(vj_files) + # Rotation : décale la liste pour répartir les quotas entre appels + _off = NanoBananaAIO._vertex_rotation_offset % len(vj_files) + vj_files = vj_files[_off:] + vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(vj_files) + print(f"🔄 [Vertex] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + vertex_json_files=vj_files, + vertex_location=v_loc, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + vertex_safety_threshold = "BLOCK_NONE" if disable_safety_threshold else None + return self._generate_vertex( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + top_p=top_p, + use_search=use_search, + system_instructions=system_instructions, + batch_size=batch_size, + vertex_json_files=vj_files, + vertex_location=v_loc, + model_name=actual_model, + safety_threshold=vertex_safety_threshold, + ) + + # ── GOOGLE ──────────────────────────────────────────── + if is_nb2: + if not g_key: + return self._handle_error( + "❌ gemini_api_key missing for Nano Banana 2 (GOOGLE)." + ) + return self._generate_nb2_google( + prompt=prompt, + image_tensors=input_images, + image_size=image_size, + aspect_ratio=aspect_ratio, + temperature=temperature, + g_key=g_key, + batch_size=batch_size, + disable_safety=disable_safety_threshold, + ) + + approach = self._detect_approach(g_key, "", "") + model_name = actual_model + + if not (1 <= batch_size <= 10): + return self._handle_error("batch_size must be between 1 and 10.") + + valid_ratios = [ + "1:1", "2:3", "3:2", "3:4", "4:3", + "4:5", "5:4", "9:16", "16:9", "21:9", + ] + if aspect_ratio not in valid_ratios: + return self._handle_error(f"Invalid ratio: {aspect_ratio}") + if image_size not in ("1K", "2K", "4K", "8K"): + return self._handle_error(f"Invalid image_size: {image_size}") + + contents = [prompt] + for i, img_tensor in enumerate(input_images, 1): + print(f"📷 Image {i} added to Google context...") + contents.append(tensor_to_pil(img_tensor)) + + common = dict( + g_key=g_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + if batch_size == 1: + return self._generate_single_image( + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + else: + return self._generate_batch_parallel( + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions, **common + ) + + except ValueError as e: + return self._handle_error(f"ValueError : {e}") + except TypeError as e: + return self._handle_error(f"TypeError : {e}") + except Exception as e: + return self._handle_error(f"{type(e).__name__} : {e}") + + # ───────────────────────────────────────────────────────────── + # _handle_error + # ───────────────────────────────────────────────────────────── + def _handle_error(self, message: str, batch_idx=None): + if batch_idx is not None: + raise RuntimeError(message) + print(f"\033[91mERROR: {message}\033[0m") + return (torch.zeros(1, 64, 64, 3), "", "") + + + + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana Pro (SDK genai) + # ───────────────────────────────────────────────────────────── + def _generate_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, top_p=0.95, + use_search=True, system_instructions=None, + batch_size=1, + vertex_json_path="", vertex_location="us-central1", + model_name="gemini-3-pro-image-preview", + safety_threshold=None, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON : liste (multi-projets) ou chemin unique + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing.", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI)...\n") + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, top_p, use_search, system_instructions, + 1, _files[i % len(_files)], vertex_location, model_name, + safety_threshold, i + 1, + ): i for i in range(batch_size) + } + _FuturesTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + try: + _completed = as_completed(futures, timeout=280) + except Exception: + _completed = as_completed(futures) + _processed = set() + try: + for future in _completed: + _processed.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=5) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + all_grounding_sources.append(result[2]) + except _FuturesTE: + errors.append(f"Batch {idx}: timeout") + print(f"❌ [Vertex Batch {idx}] Timeout — future still running") + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex Batch {idx}] Failed — {e}") + except _FuturesTE: + # as_completed outer timeout fired — salvage any completed futures + print(f"⚠️ [Vertex AI] as_completed timeout — collecting results from finished futures...") + for _f, _i in futures.items(): + if _f in _processed: + continue + _fidx = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + all_grounding_sources.append(_r[2]) + print(f"✅ [Vertex Batch {_fidx}] Recovered from completed future") + except Exception as _fe: + errors.append(f"Batch {_fidx}: {_fe}") + print(f"❌ [Vertex Batch {_fidx}] Failed — {_fe}") + else: + errors.append(f"Batch {_fidx}: outer timeout (still running)") + print(f"❌ [Vertex Batch {_fidx}] Outer timeout — still running") + + print(f"\n✨ Vertex AI — {len(generated_images)}/{batch_size} successful\n") + if errors: + for err in errors: + print(f" ⚠️ {err}") + if not generated_images: + return self._handle_error( + f"All Vertex AI generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + if errors: + combined_text = f"⚠️ {len(errors)} image(s) failed\n" + combined_text + return (combined, combined_text, combined_grounding) + + tag = f"[Vertex Batch {_batch_idx}]" if _batch_idx else "[Vertex AI]" + vertex_model_id = "gemini-3-pro-image-preview" + print(f"ℹ️ [Vertex AI] Model: {vertex_model_id}") + + try: + client = _make_vertex_client_from_json( + _files[0], vertex_location, vertex_model_id + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to create Vertex AI client: {e}", _batch_idx + ) + + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, vertex_model_id, system_instructions, safety_threshold, + ) + + contents = [prompt] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Image {i} added to context...") + contents.append(tensor_to_pil(img_tensor)) + + # Fix 3: non-streaming blocking call — more reliable than streaming for + # thinking models (avoids inter-chunk timeout race on thinking text chunk). + _VERTEX_CALL_TIMEOUT = 300 # hard cutoff total (HTTP-level + outer safety) + print(f"\U0001f680 {tag} Generating (model={vertex_model_id})...") + + def _gen_worker(): + return client.models.generate_content( + model=vertex_model_id, contents=contents, config=config + ) + + _tex = ThreadPoolExecutor(max_workers=1) + _fut = _tex.submit(_gen_worker) + + _response = None + _gen_error = None + with _Heartbeat(f"{tag} In progress"): + try: + _response = _fut.result(timeout=_VERTEX_CALL_TIMEOUT) + except Exception as _ge: + _gen_error = _ge + + _tex.shutdown(wait=False) + + image_bytes = None + text_response = "" + + if _response and not isinstance(_response, Exception): + _cands = getattr(_response, "candidates", None) or [] + for _cand in _cands: + _fr = getattr(_cand, "finish_reason", None) + if _fr and _fr not in (types.FinishReason.STOP,) \ + and str(_fr) not in ("0", "FINISH_REASON_UNSPECIFIED", "None"): + return self._handle_error( + f"\u274c {tag} Generation blocked: finish_reason={_fr}", _batch_idx + ) + _content = getattr(_cand, "content", None) + if _content and getattr(_content, "parts", None): + for _part in _content.parts: + if getattr(_part, "inline_data", None) and image_bytes is None: + image_bytes = _part.inline_data.data + elif getattr(_part, "text", None): + text_response += _part.text + + grounding_sources = self.extract_grounding_data(_response) if _response else "" + + # ── Diagnostic Vertex (lecture prompt_feedback / usage_metadata) ── + # But : transformer les "no image data" silencieux en messages + # explicites avec la raison du blocage cote serveur. + _pf_bits = [] + _meta_bits = [] + if _response and not isinstance(_response, Exception): + try: + _pf = getattr(_response, "prompt_feedback", None) \ + or getattr(_response, "promptFeedback", None) + if _pf: + _br = getattr(_pf, "block_reason", None) \ + or getattr(_pf, "blockReason", None) + _brm = getattr(_pf, "block_reason_message", None) \ + or getattr(_pf, "blockReasonMessage", None) + _sr = getattr(_pf, "safety_ratings", None) \ + or getattr(_pf, "safetyRatings", None) or [] + if _br: + _pf_bits.append(f"block_reason={_br}") + if _brm: + _pf_bits.append(f"block_message={_brm!r}") + _blocked_cats = [] + for _r in _sr: + _blk = getattr(_r, "blocked", False) + _cat = getattr(_r, "category", None) + _prb = getattr(_r, "probability", None) + if _blk: + _blocked_cats.append(f"{_cat}:{_prb}") + if _blocked_cats: + _pf_bits.append(f"blocked_categories=[{', '.join(map(str, _blocked_cats))}]") + except Exception as _e_pf: + _pf_bits.append(f"pf_parse_err={_e_pf}") + try: + _um = getattr(_response, "usage_metadata", None) \ + or getattr(_response, "usageMetadata", None) + if _um: + _ptc = getattr(_um, "prompt_token_count", None) \ + or getattr(_um, "promptTokenCount", None) + _ctc = getattr(_um, "candidates_token_count", None) \ + or getattr(_um, "candidatesTokenCount", None) + _meta_bits.append(f"tokens=in:{_ptc}/out:{_ctc}") + except Exception: + pass + try: + _cands_count = len(getattr(_response, "candidates", None) or []) + _meta_bits.append(f"candidates_count={_cands_count}") + except Exception: + pass + + # ── Diagnostic erreur SDK (headers HTTP, request_id, body) ──────── + _err_bits = [] + if _gen_error is not None: + try: + _resp = getattr(_gen_error, "response", None) + if _resp is not None: + _hdrs = dict(getattr(_resp, "headers", {}) or {}) + for _k in ("x-request-id", "X-Request-Id", "x-goog-request-id", + "x-ratelimit-remaining", "x-ratelimit-reset"): + _v = _hdrs.get(_k) + if _v: + _err_bits.append(f"{_k}={_v}") + _body = getattr(_resp, "text", None) + if _body and isinstance(_body, str): + _bsnip = _body[:300] + _err_bits.append(f"body_snippet={_bsnip!r}") + _code = getattr(_gen_error, "code", None) \ + or getattr(_gen_error, "status_code", None) + if _code: + _err_bits.append(f"http_code={_code}") + except Exception: + pass + + if image_bytes is None: + txt_preview = (text_response[:300] + "\u2026") if len(text_response) > 300 else text_response + if txt_preview: + print(f"\u26a0\ufe0f {tag} Model text-only response: {txt_preview!r}") + err_detail = f" | {type(_gen_error).__name__}: {_gen_error}" if _gen_error else "" + if _gen_error: + print(f"\u26a0\ufe0f {tag} Generation error: {_gen_error}") + # Logs diagnostic — toujours imprimer ce qu'on a, meme si vide + if _pf_bits: + print(f"\U0001f50d {tag} prompt_feedback: {' | '.join(_pf_bits)}") + if _meta_bits: + print(f"\U0001f50d {tag} response_meta: {' | '.join(_meta_bits)}") + if _err_bits: + print(f"\U0001f50d {tag} sdk_error_detail: {' | '.join(_err_bits)}") + # Concatenation dans le message d erreur final (visible dans les logs batch) + _diag_suffix = "" + if _pf_bits: + _diag_suffix += " | " + ", ".join(_pf_bits) + if _err_bits and not _gen_error: + _diag_suffix += " | " + ", ".join(_err_bits) + return self._handle_error( + f"\u274c {tag} No image data in Vertex AI response{err_detail}{_diag_suffix}.", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # VERTEX AI — Nano Banana 2 (REST OAuth2) + # ───────────────────────────────────────────────────────────── + def _generate_nb2_vertex( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, + vertex_json_path="", vertex_location="us-central1", + batch_size=1, disable_safety=False, + _batch_idx=None, + vertex_json_files=None, + ): + # Résolution des fichiers JSON + _files = vertex_json_files if vertex_json_files else ([vertex_json_path] if vertex_json_path else []) + if not _files: + return self._handle_error("❌ vertex_json missing (NB2).", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Vertex AI NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_vertex, + prompt, image_tensors, image_size, aspect_ratio, + temperature, _files[i % len(_files)], vertex_location, + 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE2 = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc2 = set() + _NB2_OUT = NB2_TIMEOUT_S + 30 + try: + for future in as_completed(futures, timeout=_NB2_OUT): + _proc2.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [Vertex NB2 Batch {idx}] Failed — {e}") + except _FTE2: + print("[Vertex NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc2: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [Vertex NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All Vertex NB2 generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[Vertex NB2 Batch {_batch_idx}]" if _batch_idx else "[Vertex AI NB2]" + + try: + if not _ensure_google_auth(): + return self._handle_error("❌ google-auth not available.", _batch_idx) + from google.oauth2 import service_account + from google.auth.transport.requests import Request as GoogleAuthRequest + + credentials, project_id = _load_vertex_credentials(_files[0]) + credentials.refresh(GoogleAuthRequest()) + access_token = credentials.token + print(f"🔑 {tag} OAuth2 token obtained (project={project_id})") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to obtain OAuth2 token: {e}", _batch_idx + ) + + vertex_nb2_model_id = "gemini-3.1-flash-image-preview" + vertex_url = ( + f"https://aiplatform.googleapis.com/v1/" + f"projects/{project_id}/locations/global/" + f"publishers/google/models/{vertex_nb2_model_id}:streamGenerateContent" + ) + + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = { + "responseModalities": ["TEXT", "IMAGE"], + "temperature": temperature, + "thinkingConfig": {"thinkingBudget": 0, "includeThoughts": False}, # disable thinking — prevents safety over-triggering + } + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + import json as _json + print(f"⏳ {tag} Sending NB2 streaming request (timeout: {NB2_TIMEOUT_S}s)...") + _hb = _Heartbeat(f"{tag} En waiting for response") + _hb.__enter__() + try: + response = requests.post( + vertex_url, json=payload, headers=headers, + timeout=NB2_TIMEOUT_S, stream=True, + ) + response.raise_for_status() + + all_candidates = [] + prompt_feedback = {} + error_chunks = [] + buffer = "" + chunk_count = 0 + raw_lines_seen = [] # garde les 5 premières lignes non-vides pour debug + + for raw_chunk in response.iter_lines(chunk_size=8192, decode_unicode=True): + if not raw_chunk: + continue + if len(raw_lines_seen) < 5: + raw_lines_seen.append(raw_chunk[:200]) + # Toujours accumuler dans le buffer (y compris [ et ]) + buffer += raw_chunk + "\n" + line = raw_chunk.strip().rstrip(",") + if line in ("[", "]"): + continue + try: + chunk = _json.loads(line) + buffer = "" # parse ligne successful, réinitialise le buffer + except Exception: + try: + chunk = _json.loads(buffer.strip()) + buffer = "" + except Exception: + continue + + # Vertex peut renvoyer la réponse en JSON array pretty-printed. + # Dans ce cas, `chunk` est une list de dicts : on la normalise. + items = chunk if isinstance(chunk, list) else [chunk] + for c in items: + if not isinstance(c, dict): + continue + if "promptFeedback" in c: + prompt_feedback = c["promptFeedback"] + + if "error" in c: + error_chunks.append(c["error"]) + + if "candidates" in c: + for cand in c["candidates"]: + finish = cand.get("finishReason", "") + if finish and finish not in ("STOP", "MAX_TOKENS", ""): + print(f"⚠️ {tag} finishReason={finish} detected in stream.") + all_candidates.extend(c["candidates"]) + chunk_count += 1 + if chunk_count == 1: + print(f" {tag} First chunk received, generating...") + # On a la réponse — stoppe le heartbeat d'attente. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ── Fallback : si le stream était pretty-printed, parser le buffer complet ── + if not all_candidates and buffer.strip(): + try: + full_parsed = _json.loads(buffer.strip()) + _items = full_parsed if isinstance(full_parsed, list) else [full_parsed] + for _c in _items: + if not isinstance(_c, dict): continue + if "promptFeedback" in _c: prompt_feedback = _c["promptFeedback"] + if "error" in _c: error_chunks.append(_c["error"]) + if "candidates" in _c: all_candidates.extend(_c["candidates"]) + if all_candidates: + print(f" {tag} Pretty-printed response parsed from complete buffer.") + except Exception as _pe: + print(f"⚠️ {tag} Complete buffer not parseable: {_pe}") + + image_bytes = None + text_response = "" + for cand in all_candidates: + for part in cand.get("content", {}).get("parts", []): + if "inlineData" in part and image_bytes is None: + image_bytes = base64.b64decode(part["inlineData"]["data"]) + elif "text" in part: + text_response += part["text"] + + if not image_bytes: + if error_chunks: + err = error_chunks[0] + code = err.get("code", "?") + msg = err.get("message", str(err)) + return self._handle_error( + f"❌ {tag} API error: code={code} — {msg}", _batch_idx + ) + if all_candidates: + finish = all_candidates[-1].get("finishReason", "?") + safety = all_candidates[-1].get("safetyRatings", []) + blocked = [r.get("category", "?") for r in safety if r.get("blocked")] + detail = f" | blocked by: {blocked}" if blocked else "" + text_in = (text_response[:200] + "…") if text_response else "(vide)" + return self._handle_error( + f"❌ {tag} No image generated (finishReason={finish}{detail})\n" + f" Text received: {text_in}", _batch_idx + ) + else: + # No candidates — blocage silencieux ou réponse vide + br = prompt_feedback.get("blockReason") or prompt_feedback.get("block_reason") + brm = prompt_feedback.get("blockReasonMessage", "") + if br: + detail = f"{br} — {brm}" if brm else br + elif prompt_feedback: + detail = f"promptFeedback={prompt_feedback}" + else: + detail = "empty response (0 candidates, no promptFeedback)" + print(f"🔍 {tag} First bytes received : {raw_lines_seen}") + return self._handle_error( + f"❌ {tag} Request blocked or empty response — {detail}", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error( + f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx + ) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + finally: + # Garantit l'arrêt du heartbeat même en cas de return/exception. + try: _hb.__exit__(None, None, None) + except Exception: pass + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedream_wavespeed( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, ws_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_wavespeed, + prompt, image_tensors, image_size, aspect_ratio, + 1, ws_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [SD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[SD Batch {_batch_idx}]" if _batch_idx else "[Seedream WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, image_size)) + if not ws_size: + ws_size = _SEEDREAM_WS_SIZE_MAP.get((aspect_ratio, "2K"), "1920*1920") + print(f"⚠️ {tag} Size not mapped → fallback {ws_size}") + + payload = { + "images": image_urls, + "prompt": prompt, + "size": ws_size, + "enable_sync_mode": False, + "enable_base64_output": False, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (size={ws_size})...") + + try: + submit_resp = requests.post( + WAVESPEED_SEEDREAM_URL, + json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: Seedream 4.5 Edit\n" + f"Size: {ws_size} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_wavespeed( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + batch_size=1, ws_api_key="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_wavespeed, + prompt, image_tensors, aspect_ratio, + image_size, 1, ws_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [GPT2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 WaveSpeed generations failed : {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[GPT2 Batch {_batch_idx}]" if _batch_idx else "[GPT Image 2.0 WS]" + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + # Upload images if provided (optional for GPT Image 2.0) + image_urls = [] + if image_tensors: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error( + f"❌ {tag} Image upload error {idx} : {e}", _batch_idx + ) + + _ws_resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") # 1k/2k/4k + _ws_quality = "high" if image_size in ("2K", "4K") else "medium" + payload = { + "prompt": prompt, + "images": image_urls if image_urls else [None], + "aspect_ratio": aspect_ratio, + "quality": _ws_quality, + "resolution": _ws_resolution, + "enable_base64_output": False, + "enable_sync_mode": False, + } + print(f"🚀 {tag} Submitting GPT Image 2.0 (aspect_ratio={aspect_ratio} | resolution={_ws_resolution} | quality={_ws_quality})...") + + try: + submit_resp = requests.post( + WAVESPEED_GPT2_URL, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + # Vérifier une erreur API-level (HTTP 200 mais corps d'erreur) + api_err = submit_data.get("error") or submit_data.get("message", "") + if api_err and str(api_err).lower() not in ("", "ok", "success"): + return self._handle_error(f"❌ {tag} API error: {api_err}", _batch_idx) + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error( + f"❌ {tag} Submission failed: {submit_data}", _batch_idx + ) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + # Statuts terminaux connus (autre que "completed") + _FAIL_STATUSES = {"failed", "error", "cancelled", "rejected", "timeout"} + # Statuts en cours : on continue de poller + _PENDING_STATUSES = {"pending", "queued", "processing", "running", "starting"} + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + # Errors HTTP fatales → pas la peine de continuer + if poll_resp.status_code in (401, 403, 404): + return self._handle_error( + f"❌ {tag} Error HTTP {poll_resp.status_code} during polling.", _batch_idx + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status in _FAIL_STATUSES: + error_msg = poll_data.get("data", {}).get("error") or f"Status : {status}" + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + elif status and status not in _PENDING_STATUSES: + # Status inattendu et non-pending → on sort immédiatement + error_msg = poll_data.get("data", {}).get("error") or f"Status inattendu : {status!r}" + return self._handle_error(f"❌ {tag} Stopped: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: GPT Image 2.0\n" + f"Aspect ratio: {aspect_ratio} | Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KSD Batch {_batch_idx}]" if _batch_idx else "[Kie.ai Seedream]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + quality = "high" if image_size == "4K" else "basic" + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : si une seule ref a echoue a l'upload, on aborte plutot + # que de laisser Kie generer en text-to-image silencieusement. + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references. Check network/firewall (catbox/litterbox/0x0.st/telegra.ph all failed).", + _batch_idx, + ) + + nsfw_checker = not disable_safety + payload = { + "model": KIE_SEEDREAM_MODEL, + "input": { + "prompt": prompt, + "image_urls": image_urls, + "aspect_ratio": aspect_ratio, + "quality": quality, + "nsfw_checker": nsfw_checker, + }, + } + print(f"🚀 {tag} Submitting Seedream 4.5 (quality={quality})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: Seedream 4.5 Edit\n" + f"Quality: {quality} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_kie( + self, + prompt, image_tensors, aspect_ratio="1:1", + image_size="2K", + kie_api_key="", ws_api_key="", + batch_size=1, disable_safety=False, + _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_kie, + prompt, image_tensors, aspect_ratio, + image_size, kie_api_key, ws_api_key, 1, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KGP2 Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 Kie generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KGP2 Batch {_batch_idx}]" if _batch_idx else "[Kie.ai GPT Image 2.0]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Choisir le model selon présence ou non d'images source + has_images = bool(image_tensors) + kie_model = "gpt-image-2-image-to-image" if has_images else "gpt-image-2-text-to-image" + + # Upload des images source via WaveSpeed si présentes + image_urls = [] + if has_images: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si toutes OU partiellement les refs ont echoue + if not image_urls: + return self._handle_error( + f"❌ {tag} Image upload failed (ws_api_key required for img2img).", _batch_idx + ) + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload partiel: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your full references.", + _batch_idx, + ) + + nsfw_checker = not disable_safety + # KIE : 4K incompatible with 1:1 and auto aspect_ratio → fallback 2K + _kie_resolution = image_size + if image_size == "4K" and aspect_ratio in ("1:1", "auto"): + print(f"⚠️ {tag} KIE GPT2: 4K incompatible with aspect_ratio={aspect_ratio!r} → fallback 2K") + _kie_resolution = "2K" + if has_images: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "input_urls": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + else: + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "resolution": _kie_resolution, + "nsfw_checker": nsfw_checker, + }, + } + + mode_label = "img2img" if has_images else "txt2img" + print(f"🚀 {tag} Submitting GPT Image 2.0 [{mode_label}] (ratio={aspect_ratio})...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {KIE_TIMEOUT_S}s)...") + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} No URL in resultJson.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing resultJson : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Ratio: {aspect_ratio} | Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # SEEDREAM 4.5 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedream_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", + disable_safety=False, _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + endpoint = FAL_SEEDREAM_ENDPOINT + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai Seedream 4.5)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_seedream_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, disable_safety, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FSD Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Seedream FAL generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FSD Batch {_batch_idx}]" if _batch_idx else "[Fal.ai Seedream]" + fal_image_size = "auto_4K" if image_size == "4K" else "auto_2K" + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_urls": image_urls, + "image_size": fal_image_size, + "num_images": 1, + "enable_safety_checker": not disable_safety, + } + print(f"🚀 {tag} Submitting → {endpoint}") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: Seedream 4.5 Edit\n" + f"Taille : {fal_image_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # GPT IMAGE 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_gpt2_fal( + self, + prompt, image_tensors, aspect_ratio="1:1", image_size="2K", + gpt2_quality="high", batch_size=1, fal_api_key="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai GPT Image 2.0)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_gpt2_fal, + prompt, image_tensors, aspect_ratio, image_size, + gpt2_quality, 1, fal_api_key, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + short_e = _fal_short_error(e) + errors.append(f"Batch {idx}: {short_e}") + print(f"❌ [FGP2 Batch {idx}] Failed — {short_e}") + + if not generated_images: + return self._handle_error( + f"All GPT Image 2.0 FAL generations failed:\n" + "\n".join(errors) + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + has_images = bool(image_tensors) + endpoint = FAL_GPT2_EDIT_ENDPOINT if has_images else FAL_GPT2_TXT2IMG_ENDPOINT + tag = f"[FGP2 Batch {_batch_idx}]" if _batch_idx else "[Fal.ai GPT Image 2.0]" + mode_label = "img2img" if has_images else "txt2img" + + # Résolution : lookup dans la table, fallback "auto" pour edit + fal_size = _GPT2_FAL_SIZE_MAP.get((aspect_ratio, image_size)) + if fal_size is None: + fal_size = "auto" if has_images else "landscape_4_3" + print(f"⚠️ {tag} Combo ({aspect_ratio}, {image_size}) not mapped → fallback {fal_size!r}") + + # Upload images si présentes + image_urls = [] + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + + arguments = { + "prompt": prompt, + "image_size": fal_size, + "quality": gpt2_quality, + "num_images": 1, + "output_format": "png", + } + if has_images: + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}] (size={fal_size!r}, quality={gpt2_quality})") + + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + elapsed = 0 + while elapsed < FAL_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s] Queue position={pos}") + else: + print(f" {tag} [{elapsed}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {FAL_TIMEOUT_S}s.", _batch_idx) + + result_data = fal_client.result(endpoint, request_id) + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + info = ( + f"[Fal.ai] Model: GPT Image 2.0 [{mode_label}]\n" + f"Taille : {fal_size} | {img_info.get('width','?')}x{img_info.get('height','?')}px\n" + f"Quality: {gpt2_quality} | Total time: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}", _batch_idx + ) + + # ───────────────────────────────────────────────────────────── + # FAL.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_fal( + self, + prompt, image_tensors, image_size, aspect_ratio, + batch_size=1, fal_api_key="", is_nb2=False, + safety_tolerance="4", enable_web_search=False, + negative_prompt="", + _batch_idx=None, + ): + if not fal_api_key: + return self._handle_error("❌ fal_api_key missing!", _batch_idx) + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.", _batch_idx) + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + has_images = bool(image_tensors) + if is_nb2: + endpoint = FAL_NB2_EDIT_ENDPOINT if has_images else FAL_NB2_T2I_ENDPOINT + else: + endpoint = FAL_PRO_EDIT_ENDPOINT if has_images else FAL_PRO_T2I_ENDPOINT + + model_label = endpoint + mode_label = "img2img" if has_images else "text-to-image" + print(f"ℹ️ [Fal.ai] Mode : {mode_label} → {endpoint}") + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Fal.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_fal, + prompt, image_tensors, image_size, aspect_ratio, + 1, fal_api_key, is_nb2, safety_tolerance, enable_web_search, + negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [FAL Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Fal.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[FAL Batch {_batch_idx}]" if _batch_idx else "[Fal.ai]" + arguments = { + "prompt": prompt, + "resolution": image_size, + "aspect_ratio": aspect_ratio, + "output_format": "png", + "safety_tolerance": safety_tolerance, + "enable_web_search": enable_web_search, + "limit_generations": True, + "num_images": 1, + } + if negative_prompt and negative_prompt.strip(): + arguments["negative_prompt"] = negative_prompt.strip() + + if has_images: + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for i, tensor in enumerate(image_tensors, 1): + try: + url = _tensor_to_fal_url(tensor, fal_client, tag=tag, idx=i) + image_urls.append(url) + except Exception as e: + return self._handle_error(f"❌ {tag} Image upload error {i} : {e}", _batch_idx) + arguments["image_urls"] = image_urls + + print(f"🚀 {tag} Submitting → {endpoint} [{mode_label}]") + + import time as _time + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + + fal_images = result_data.get("images", []) + if not fal_images: + return self._handle_error(f"❌ {tag} Aucune image : {result_data}", _batch_idx) + img_info = fal_images[0] + output_url = img_info.get("url", "") + if not output_url: + return self._handle_error(f"❌ {tag} URL missing.", _batch_idx) + + print(f"✅ {tag} Image ready! ({elapsed}s)") + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + w = img_info.get("width", "?") + h = img_info.get("height", "?") + info = ( + f"[Fal.ai] {model_label} [{mode_label}]\n" + f"Taille : {image_size} | {w}x{h}px | Temps total : {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Error: {type(e).__name__} : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # NANO BANANA 2 — Google REST + # ───────────────────────────────────────────────────────────── + def _generate_nb2_google( + self, + prompt, image_tensors, image_size, aspect_ratio, + temperature=1.0, g_key="", batch_size=1, + disable_safety=False, _batch_idx=None, + ): + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Google NB2)...\n") + generated_images = [] + all_text_responses = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_nb2_google, + prompt, image_tensors, image_size, aspect_ratio, + temperature, g_key, 1, disable_safety, i + 1, + ): i for i in range(batch_size) + } + _FTE = __import__('concurrent.futures', fromlist=['TimeoutError']).TimeoutError + _proc = set() + try: + for future in as_completed(futures, timeout=NB2_TIMEOUT_S + 30): + _proc.add(future) + idx = futures[future] + 1 + try: + result = future.result(timeout=10) + generated_images.append(result[0]) + all_text_responses.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [NB2 Batch {idx}] Failed — {e}") + except _FTE: + print("[Google NB2] timeout — salvaging completed futures...") + for _f, _i in futures.items(): + if _f in _proc: continue + _fi = _i + 1 + if _f.done(): + try: + _r = _f.result(timeout=0) + generated_images.append(_r[0]) + all_text_responses.append(_r[1]) + print(f"✅ [NB2 Batch {_fi}] Recovered") + except Exception as _fe: + errors.append(f"Batch {_fi}: {_fe}") + else: + errors.append(f"Batch {_fi}: outer timeout") + + if not generated_images: + return self._handle_error( + f"All NB2 generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + if errors: + combined_text = f"⚠️ {len(errors)} error(s)\n" + combined_text + return (combined, combined_text, "") + + tag = f"[NB2 Batch {_batch_idx}]" if _batch_idx else "[Google NB2]" + parts = [] + for i, img_tensor in enumerate(image_tensors, 1): + print(f"📷 {tag} Adding image {i}...") + parts.append(_tensor_to_base64_part(img_tensor)) + parts.append({"text": prompt}) + + image_config = {} + if aspect_ratio and aspect_ratio != "auto": + image_config["aspectRatio"] = aspect_ratio + if image_size: + image_config["imageSize"] = image_size + + gen_config: dict = {"responseModalities": ["TEXT", "IMAGE"], "temperature": temperature} + if image_config: + gen_config["imageConfig"] = image_config + + safety_settings = [ + {"category": cat, "threshold": "OFF"} for cat in _HARM_CATEGORIES + ] + payload = { + "contents": [{"role": "user", "parts": parts}], + "systemInstruction": {"parts": [{"text": NB2_SYSTEM_PROMPT}]}, + "generationConfig": gen_config, + "safetySettings": safety_settings, + } + url = f"{NB2_BASE_URL}?key={g_key}" + + print(f"⏳ {tag} Sending NB2 request (timeout: {NB2_TIMEOUT_S}s)...") + try: + with _Heartbeat(f"{tag} In progress"): + response = requests.post( + url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=NB2_TIMEOUT_S, + ) + response.raise_for_status() + try: + data = response.json() + except ValueError as e: + return self._handle_error(f"❌ {tag} Invalid JSON response : {e}", _batch_idx) + + image_bytes = _extract_image_bytes_from_nb2_response(data) + + if not image_bytes: + candidates = data.get("candidates", []) + if candidates: + finish = candidates[0].get("finishReason", "?") + safety = candidates[0].get("safetyRatings", []) + blocked = [r for r in safety if r.get("blocked")] + detail = f", blocked by: {blocked}" if blocked else "" + return self._handle_error( + f"❌ {tag} Aucune image (finishReason={finish}{detail}).", _batch_idx + ) + else: + feedback = data.get("promptFeedback", {}) + block_reason = feedback.get("blockReason", "?") + return self._handle_error( + f"❌ {tag} Request blocked by API (blockReason={block_reason}).", _batch_idx + ) + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + text_response = "" + for cand in data.get("candidates", []): + for part in cand.get("content", {}).get("parts", []): + if "text" in part: + text_response += part["text"] + + print(f"✅ {tag} Generation successful!") + return (image_tensor, text_response, "") + + except requests.exceptions.Timeout: + return self._handle_error(f"❌ {tag} Timeout after {NB2_TIMEOUT_S}s.", _batch_idx) + except requests.exceptions.HTTPError as e: + try: + body = e.response.json() + except Exception: + body = e.response.text + return self._handle_error(f"❌ {tag} HTTP {e.response.status_code} : {body}", _batch_idx) + except requests.exceptions.RequestException as e: + return self._handle_error(f"❌ {tag} Network error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helpers Google SDK + # ───────────────────────────────────────────────────────────── + def _detect_approach(self, g_key: str, v_proj: str, v_loc: str) -> str: + if g_key: + return "API" + raise RuntimeError( + "❌ No Google API key configured!\n" + "→ Connect an 'API Keys Loader' node and wire gemini_api_key." + ) + + def _make_google_client(self, approach, g_key, v_proj="", v_loc="", model_name=""): + if not g_key: + raise RuntimeError("❌ gemini_api_key missing !") + # Note: HttpOptions(timeout=...) retiré — certaines versions du SDK + # google-genai propagent ce timeout comme kwarg `timeout=` sur + # generate_content(), ce qui plante en mode batch parallèle. + # Le timeout est déjà géré par _Heartbeat(max_duration=...) côté batch. + return genai.Client(api_key=g_key) + + def _create_config( + self, + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, + system_instructions=None, safety_threshold=None, + ): + if "preview" in model_name and not self._preview_warning_shown: + print(f"⚠️ Using a preview model: {model_name}") + self._preview_warning_shown = True + + if safety_threshold is not None: + safety_settings = [ + types.SafetySetting(category=cat, threshold=safety_threshold) + for cat in _HARM_CATEGORIES + ] + else: + safety_settings = None + + config_kwargs = dict( + response_modalities=["TEXT", "IMAGE"], + image_config=types.ImageConfig(aspect_ratio=aspect_ratio, image_size=image_size), + temperature=temperature, + top_p=top_p, + automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True), + ) + # Disable thinking mode — gemini-3-pro-image-preview uses its full token + # budget "reasoning" and never outputs an image if thinking is enabled. + try: + config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=0) + print("🧠 [Config] ThinkingConfig(thinking_budget=0) applied via class") + except AttributeError: + # Older SDK: pass as raw dict — google-genai accepts dicts for nested configs + try: + config_kwargs["thinking_config"] = {"thinking_budget": 0} + print("🧠 [Config] ThinkingConfig applied via dict fallback") + except Exception as _te: + print(f"⚠️ [Config] Could not disable thinking mode: {_te} — consider: pip install --upgrade google-genai") + if safety_settings is not None: + config_kwargs["safety_settings"] = safety_settings + + config = types.GenerateContentConfig(**config_kwargs) + + if system_instructions and system_instructions.strip(): + config.system_instruction = system_instructions + + if use_search: + try: + config.tools = [types.Tool(google_search=types.GoogleSearch())] + except Exception as e: + print(f"⚠️ Search tool not supported: {e}") + + return config + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — génération simple + # ───────────────────────────────────────────────────────────── + def _generate_single_image( + self, + model_name, prompt, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + print("🚀 Google — generation in progress...") + with _Heartbeat("[Google] In progress"): + response = client.models.generate_content( + model=model_name, contents=contents, config=config + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + return self._handle_error(f"Google API returned no candidates (blockReason={reason}).") + + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + return self._handle_error(f"Google generation failed : {cand.finish_reason}") + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + return self._handle_error("No image data in Google response.") + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print("✅ Google — generation successful!") + return (image_tensor, text_response, grounding_sources) + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — tâche unitaire batch + # ───────────────────────────────────────────────────────────── + def _generate_one_image_task( + self, task_id, model_name, contents, config, + approach, g_key="", v_proj="", v_loc="", + ): + try: + print(f"🚀 [Batch {task_id}] Starting...") + client = self._make_google_client(approach, g_key, v_proj, v_loc, model_name) + with _Heartbeat(f"[Batch {task_id}] In progress", + max_duration=GOOGLE_TASK_TIMEOUT_S): + # NB: le timeout est appliqué via HttpOptions à la création du + # client (cf. _make_google_client). La SDK google-genai + # n'accepte PAS de kwarg `timeout` sur generate_content(). + response = client.models.generate_content( + model=model_name, contents=contents, config=config, + ) + if not response.candidates: + reason = "?" + try: + pf = response.prompt_feedback + if pf: + reason = str(getattr(pf, "block_reason", None) or getattr(pf, "blockReason", "?")) + except Exception: + pass + err = f"No candidates — request blocked (blockReason={reason})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + cand = response.candidates[0] + _VALID_FINISH = { + types.FinishReason.STOP, + getattr(types.FinishReason, "IMAGE_GENERATION_STOP", types.FinishReason.STOP), + } + if hasattr(cand, "finish_reason") and cand.finish_reason not in _VALID_FINISH: + err = f"finish_reason inattendu : {cand.finish_reason}" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, + "image_tensor": None, "text_response": "", "grounding_sources": ""} + + image_bytes = None + text_response = "" + for part in cand.content.parts: + if part.inline_data and image_bytes is None: + image_bytes = part.inline_data.data + elif part.text: + text_response += part.text + + grounding_sources = self.extract_grounding_data(response) + + if image_bytes is None: + err = f"No image data (finish_reason={getattr(cand, 'finish_reason', '?')})" + print(f"⚠️ [Batch {task_id}] {err}") + return {"success": False, "error": err, "image_tensor": None, + "text_response": text_response, "grounding_sources": grounding_sources} + + pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") + image_np = np.array(pil_image).astype(np.float32) / 255.0 + image_tensor = torch.from_numpy(image_np)[None,] + print(f"✅ [Batch {task_id}] Success!") + return {"success": True, "image_tensor": image_tensor, + "text_response": text_response, "grounding_sources": grounding_sources, "error": None} + except Exception as e: + print(f"❌ [Batch {task_id}] Exception : {e}") + return {"success": False, "error": str(e), "image_tensor": None, + "text_response": "", "grounding_sources": ""} + + # ───────────────────────────────────────────────────────────── + # GOOGLE SDK — batch parallèle + # ───────────────────────────────────────────────────────────── + def _generate_batch_parallel( + self, + model_name, prompt, batch_size, use_search, approach, contents, + aspect_ratio, image_size, temperature, top_p, + system_instructions=None, + g_key="", v_proj="", v_loc="", safety_threshold=None, + ): + print(f"\n🔥 Parallel generation of {batch_size} images (Google)...\n") + config = self._create_config( + aspect_ratio, image_size, temperature, top_p, + use_search, model_name, system_instructions, safety_threshold, + ) + generated_images = [] + all_text_responses = [] + all_grounding_sources = [] + errors = [] + + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = { + executor.submit( + self._generate_one_image_task, + i + 1, model_name, contents, copy.deepcopy(config), approach, g_key, v_proj, v_loc, + ): i for i in range(batch_size) + } + try: + for future in as_completed(futures, timeout=GOOGLE_TASK_TIMEOUT_S): + task_id = futures[future] + 1 + try: + result = future.result(timeout=10) + except Exception as e: + err_msg = str(e) + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + continue + if result["success"]: + generated_images.append(result["image_tensor"]) + all_text_responses.append(result["text_response"]) + all_grounding_sources.append(result["grounding_sources"]) + else: + err_msg = result['error'] + errors.append(f"Batch {task_id}: {err_msg}") + print(f"❌ [Batch {task_id}] Failed — {err_msg}") + except TimeoutError: + # Une ou plusieurs tâches n'ont pas répondu dans le délai imparti + timed_out = [futures[f] + 1 for f in futures if not f.done()] + for tid in timed_out: + msg = f"Timeout after {GOOGLE_TASK_TIMEOUT_S}s (Google SDK did not respond)" + errors.append(f"Batch {tid}: {msg}") + print(f"❌ [Batch {tid}] {msg}") + + print(f"\n✨ Done! {len(generated_images)}/{batch_size} successful\n") + if errors: + print(f"⚠️ Failures ({len(errors)}): {' | '.join(errors)}\n") + if not generated_images: + return self._handle_error(f"All generations failed : {'; '.join(errors)}") + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined_images = torch.cat(valid_images, dim=0) + combined_text = "\n\n".join(all_text_responses) + combined_grounding = "\n\n".join(all_grounding_sources) + return (combined_images, combined_text, combined_grounding) + + # ───────────────────────────────────────────────────────────── + # WAVESPEED — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_wavespeed( + self, + prompt, image_tensors, image_size, output_format, + aspect_ratio="1:1", batch_size=1, + ws_api_key="", is_nb2=False, + negative_prompt="", + _batch_idx=None, + ): + if not ws_api_key: + return self._handle_error("❌ wavespeed_api_key missing!", _batch_idx) + if not image_tensors: + return self._handle_error("❌ WaveSpeed requires at least one source image.", _batch_idx) + + # NB Pro 4K/8K → edit-ultra endpoint + _use_ultra = (not is_nb2) and (image_size in ("4K", "8K")) + if is_nb2: + submit_url = WAVESPEED_SUBMIT_NB2_URL + model_label = "nano-banana-2/edit" + elif _use_ultra: + submit_url = WAVESPEED_SUBMIT_PRO_ULTRA_URL + model_label = "nano-banana-pro/edit-ultra" + else: + submit_url = WAVESPEED_SUBMIT_PRO_URL + model_label = "nano-banana-pro/edit" + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (WaveSpeed)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_wavespeed, + prompt, image_tensors, image_size, output_format, + aspect_ratio, 1, ws_api_key, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [WS Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All WaveSpeed generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[WS Batch {_batch_idx}]" if _batch_idx else "[WaveSpeed]" + resolution = SIZE_TO_RESOLUTION.get(image_size, "2k") + headers_auth = {"Authorization": f"Bearer {ws_api_key}"} + + print(f"⬆️ {tag} Uploading {len(image_tensors)} image(s)...") + image_urls = [] + for idx, img_tensor in enumerate(image_tensors, 1): + try: + pil_image = tensor_to_pil(img_tensor) + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + img_buffer.seek(0) + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, headers=headers_auth, + files={"file": (f"source_{idx}.png", img_buffer, "image/png")}, + timeout=60, + ) + upload_resp.raise_for_status() + upload_data = upload_resp.json() + image_url = upload_data.get("data", {}).get("download_url") + if not image_url: + return self._handle_error( + f"❌ {tag} Image {idx} upload failed : {upload_data}", _batch_idx + ) + image_urls.append(image_url) + print(f"✅ {tag} Image {idx}/{len(image_tensors)} uploaded") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Image upload error {idx} : {e}", _batch_idx) + + payload = { + "prompt": prompt, + "images": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "output_format": output_format, + "enable_base64_output": False, + "enable_sync_mode": False, + "enable_web_search": False, + "enable_image_search": False, + } + if negative_prompt and negative_prompt.strip(): + payload["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting ({model_label}, resolution={resolution})...") + + try: + submit_resp = requests.post( + submit_url, json=payload, + headers={**headers_auth, "Content-Type": "application/json"}, + timeout=30, + ) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + body = "" + try: + body = e.response.text + except Exception: + pass + return self._handle_error(f"❌ {tag} Submission error : {e} | Body: {body}", _batch_idx) + + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {WAVESPEED_TIMEOUT_S}s)...") + while elapsed < WAVESPEED_TIMEOUT_S: + time.sleep(WAVESPEED_POLL_DELAY) + elapsed += WAVESPEED_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers=headers_auth, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no output.", _batch_idx) + output_url = outputs[0] + print(f"✅ {tag} Image ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}", _batch_idx) + else: + print(f" {tag} [{elapsed}s/{WAVESPEED_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete(WAVESPEED_CANCEL_URL.format(task_id=task_id), headers=headers_auth, timeout=10) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {WAVESPEED_TIMEOUT_S}s.", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + timing_ms = poll_data.get("data", {}).get("timings", {}).get("inference", 0) + info = ( + f"[WaveSpeed] Model: google/{model_label}\n" + f"Resolution: {image_size} | Format: {output_format}\n" + f"Inference time: {timing_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Helper URL publique + # + # IMPORTANT pour les futures additions de modeles Kie : + # ---------------------------------------------------- + # Quand tu ajoutes une nouvelle fonction _generate__kie(...) qui + # appelle ce helper pour uploader des images de reference : + # + # 1. Ajoute "kie_api_key" dans la signature de ta fonction (str = "") + # 2. Passe-le au helper : self._tensor_to_public_url( + # tensor, idx=i, + # ws_api_key=ws_api_key, + # kie_api_key=kie_api_key, # <-- ESSENTIEL pour les modeles Kie + # ) + # 3. Pour les modeles NON-Kie (Wavespeed/Fal/Vertex/...), NE PAS passer + # kie_api_key — laisse-le defaut "". Ils utiliseront la chaine + # de fallback classique (catbox/litterbox/etc.). + # + # Pourquoi : avec kie_api_key, le helper essaie d'abord l'API d'upload de + # Kie (https://kieai.redpandaai.co/api/file-stream-upload). L'image est + # directement chez Kie -> evite les erreurs E9243 ("Director: unexpected + # error handling prediction") quand Kie n'arrive pas a fetcher une URL + # externe (catbox bloque par leur WAF, WaveSpeed CDN inaccessible, etc.). + # ───────────────────────────────────────────────────────────── + def _tensor_to_public_url(self, img_tensor, idx: int = 1, ws_api_key: str = "", kie_api_key: str = "") -> str | None: + """Convert a tensor to a publicly fetchable URL via cascading uploads. + + Upload chain (priorite decroissante) : + 0. Kie file-stream-upload (si kie_api_key fourni) ← recommande pour les jobs Kie + 1. WaveSpeed CDN (si ws_api_key fourni) + 2. catbox.moe (anonymous) + 3. litterbox.catbox.moe (anonymous, 1h TTL) + 4. 0x0.st (anonymous) + 5. telegra.ph (anonymous) + + Returns the first successful URL, or None if all services fail. + + Compression auto : si le PNG depasse 10 MB (limite Kie file-upload), + recodage en JPEG quality 92 -> 85 -> 75 -> 65 jusqu'a passer sous 10 MB. + Cible ~6 MB pour garder une bonne marge. Le buffer JPEG est ensuite + utilise pour TOUS les services d'upload (plus rapide et plus fiable + sur connexions instables). + + Args: + img_tensor: ComfyUI image tensor [1, H, W, 3] float 0..1 + idx: Image index (1-based) — used for the filename + ws_api_key: WaveSpeed API key — active la fallback WaveSpeed CDN + kie_api_key: Kie API key — active l'upload Kie en priorite 0. + A passer UNIQUEMENT depuis les fonctions Kie ; pour + les autres providers (Wavespeed/Fal/Vertex/Google), + laisser defaut "". + """ + pil_image = tensor_to_pil(img_tensor) + if pil_image is None: + return None + img_buffer = io.BytesIO() + pil_image.save(img_buffer, format="PNG") + + # ── Compression JPEG conditionnelle (si > 10 MB, limite Kie) ── + SIZE_LIMIT_BYTES = 10 * 1024 * 1024 # 10 MB + png_size = img_buffer.tell() + upload_filename = f"kie_input_{idx}.png" + upload_mimetype = "image/png" + + if png_size > SIZE_LIMIT_BYTES: + print(f"ℹ️ [Upload] Image {idx} PNG = {png_size / 1024 / 1024:.1f} MB > 10 MB limit → recoding to JPEG") + # JPEG ne supporte pas RGBA → convert RGB d'abord + rgb_image = pil_image.convert("RGB") if pil_image.mode != "RGB" else pil_image + jpeg_buffer = None + jpg_size = 0 + for q in (92, 85, 75, 65): + jpeg_buffer = io.BytesIO() + rgb_image.save(jpeg_buffer, format="JPEG", quality=q, optimize=True) + jpg_size = jpeg_buffer.tell() + if jpg_size <= SIZE_LIMIT_BYTES: + print(f" [Upload] JPEG quality={q} → {jpg_size / 1024 / 1024:.2f} MB (was {png_size / 1024 / 1024:.1f} MB PNG)") + break + else: + # Aucune qualite n'a passe — on garde la derniere (Q=65). + print(f"⚠️ [Upload] Image {idx} still {jpg_size / 1024 / 1024:.1f} MB at JPEG q=65 (uploads may fail).") + img_buffer = jpeg_buffer + upload_filename = f"kie_input_{idx}.jpg" + upload_mimetype = "image/jpeg" + + _skip = NanoBananaAIO._failed_upload_services + + # --- Priorité 0 : Kie file-stream-upload (recommandé par Kie support) --- + # Avantage : l'image est directement chez Kie, pas de fetch externe. + # Évite les erreurs E9243 (Director: unexpected error handling prediction) + # quand Kie n'arrive pas à fetcher une URL externe (catbox/WS/etc). + # NOTE : on NE skip PAS Kie upload entre tentatives — c'est la methode + # recommandee par leur support, on doit la tenter a chaque appel. + if kie_api_key: + img_buffer.seek(0) + try: + kie_resp = requests.post( + "https://kieai.redpandaai.co/api/file-stream-upload", + headers={"Authorization": f"Bearer {kie_api_key}"}, + files={"file": (upload_filename, img_buffer, upload_mimetype)}, + data={"uploadPath": "images/user-uploads"}, + timeout=60, + ) + kie_resp.raise_for_status() + _kj = kie_resp.json() + _url = ( + (_kj.get("data") or {}).get("downloadUrl") + or _kj.get("downloadUrl") + ) + if _url: + print(f"✅ [Upload] Image {idx} → Kie : {_url}") + return _url + print(f"⚠️ [Upload] Kie response missing downloadUrl: {_kj} — falling back to other services for this image.") + except Exception as e: + print(f"⚠️ [Upload] Kie file-upload failed ({e}) — falling back to other services for this image.") + + # --- WaveSpeed CDN (requires ws_api_key) --- + if ws_api_key and "wavespeed" not in _skip: + img_buffer.seek(0) + try: + upload_resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (upload_filename, img_buffer, upload_mimetype)}, + timeout=60, + ) + upload_resp.raise_for_status() + url = upload_resp.json().get("data", {}).get("download_url") + if url: + print(f"✅ [Upload] Image {idx} → OK") + return url + except Exception as e: + print(f"⚠️ [Upload] WaveSpeed CDN failed ({e}) — skipping for this session.") + _skip.add("wavespeed") + + # --- Fallback 1 : catbox.moe --- + if "catbox" not in _skip: + img_buffer.seek(0) + try: + catbox_resp = requests.post( + "https://catbox.moe/user/api.php", + data={"reqtype": "fileupload"}, + files={"fileToUpload": (upload_filename, img_buffer, upload_mimetype)}, + timeout=30, + ) + catbox_resp.raise_for_status() + url = catbox_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → catbox.moe : {url}") + return url + _skip.add("catbox") + except Exception as e: + print(f"⚠️ [Upload] catbox.moe failed ({e}) — skipping for this session.") + _skip.add("catbox") + + # --- Fallback 2 : litterbox.catbox.moe --- + if "litterbox" not in _skip: + img_buffer.seek(0) + try: + litter_resp = requests.post( + "https://litterbox.catbox.moe/resources/internals/api.php", + data={"reqtype": "fileupload", "time": "1h"}, + files={"fileToUpload": (upload_filename, img_buffer, upload_mimetype)}, + timeout=30, + ) + litter_resp.raise_for_status() + url = litter_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → litterbox : {url}") + return url + _skip.add("litterbox") + except Exception as e: + print(f"⚠️ [Upload] litterbox failed ({e}) — skipping for this session.") + _skip.add("litterbox") + + # --- Fallback 3 : 0x0.st --- + if "0x0" not in _skip: + img_buffer.seek(0) + try: + zero_resp = requests.post( + "https://0x0.st", + files={"file": (upload_filename, img_buffer, upload_mimetype)}, + timeout=30, + ) + zero_resp.raise_for_status() + url = zero_resp.text.strip() + if url.startswith("https://"): + print(f"✅ [Upload] Image {idx} → 0x0.st : {url}") + return url + _skip.add("0x0") + except Exception as e: + print(f"⚠️ [Upload] 0x0.st failed ({e}) — skipping for this session.") + _skip.add("0x0") + + # --- Fallback 4 : telegra.ph --- + if "telegraph" not in _skip: + img_buffer.seek(0) + try: + tph_resp = requests.post( + "https://telegra.ph/upload", + files={"file": (upload_filename, img_buffer, upload_mimetype)}, + timeout=30, + ) + tph_resp.raise_for_status() + tph_data = tph_resp.json() + tph_path = tph_data[0].get("src", "") if isinstance(tph_data, list) else "" + if tph_path.startswith("/"): + url = f"https://telegra.ph{tph_path}" + print(f"✅ [Upload] Image {idx} → telegra.ph : {url}") + return url + _skip.add("telegraph") + except Exception as e: + print(f"⚠️ [Upload] telegra.ph failed ({e}) — skipping for this session.") + _skip.add("telegraph") + + print(f"❌ [Upload] All upload services failed for image {idx}.") + return None + + # ───────────────────────────────────────────────────────────── + # KIE.AI — NB Pro / NB2 + # ───────────────────────────────────────────────────────────── + def _generate_kie( + self, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key="", ws_api_key="", batch_size=1, + is_nb2=False, negative_prompt="", _batch_idx=None, + ): + if not kie_api_key: + return self._handle_error("❌ kie_api_key missing!", _batch_idx) + + kie_model = "nano-banana-2" if is_nb2 else "nano-banana-pro" + model_label = kie_model + + if batch_size and batch_size > 1: + print(f"\n🔥 Parallel generation of {batch_size} images (Kie.ai)...\n") + generated_images = [] + all_info = [] + errors = [] + with ThreadPoolExecutor(max_workers=batch_size) as executor: + futures = {} + for i in range(batch_size): + fut = executor.submit( + self._generate_kie, + prompt, image_tensors, image_size, aspect_ratio, + kie_api_key, ws_api_key, 1, is_nb2, negative_prompt, i + 1, + ) + futures[fut] = i + for future in as_completed(futures): + idx = futures[future] + 1 + try: + result = future.result() + generated_images.append(result[0]) + all_info.append(result[1]) + except Exception as e: + errors.append(f"Batch {idx}: {e}") + print(f"❌ [KIE Batch {idx}] Failed — {e}") + + if not generated_images: + return self._handle_error( + f"All Kie.ai generations failed: {'; '.join(errors)}" + ) + ref_shape = generated_images[0].shape + valid_images = [img for img in generated_images if img.shape == ref_shape] + if not valid_images: + return self._handle_error("No valid image.") + combined = torch.cat(valid_images, dim=0) + combined_info = "\n\n".join(all_info) + if errors: + combined_info = f"⚠️ {len(errors)} image(s) failed\n" + combined_info + return (combined, combined_info, "") + + tag = f"[KIE Batch {_batch_idx}]" if _batch_idx else "[Kie.ai]" + headers = {"Authorization": f"Bearer {kie_api_key}", "Content-Type": "application/json"} + + image_urls = [] + if image_tensors: + print(f"🖼️ {tag} Converting {len(image_tensors)} image(s)...") + for i, tensor in enumerate(image_tensors, 1): + url = self._tensor_to_public_url(tensor, idx=i, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + # Fail-fast : aborte si une seule ref n'a pas pu etre uploadee + if len(image_urls) < len(image_tensors): + _missing = len(image_tensors) - len(image_urls) + return self._handle_error( + f"❌ {tag} Upload failed: {len(image_urls)}/{len(image_tensors)} reference image(s) " + f"uploaded ({_missing} missing). Generation aborted to avoid producing an image without " + f"your references.", + _batch_idx, + ) + + payload = { + "model": kie_model, + "input": { + "prompt": prompt, + "image_input": image_urls, + "aspect_ratio": aspect_ratio, + "resolution": image_size, + "output_format": "png", + }, + } + if negative_prompt and negative_prompt.strip(): + payload["input"]["negative_prompt"] = negative_prompt.strip() + print(f"🚀 {tag} Submitting {model_label}...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}", _batch_idx) + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission failed: {data.get('msg', 'unknown error')}", _batch_idx + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}", _batch_idx) + print(f"🔖 {tag} Task ID : {task_id}") + + elapsed = 0 + result_data = {} + while elapsed < KIE_TIMEOUT_S: + time.sleep(KIE_POLL_DELAY) + elapsed += KIE_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error(f"❌ {tag} Poll error: {poll_data.get('msg')}", _batch_idx) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}", _batch_idx + ) + else: + print(f" {tag} [{elapsed}s/{KIE_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {KIE_TIMEOUT_S}s.", _batch_idx) + + try: + import json as _json + result_json = _json.loads(result_data.get("resultJson", "{}")) + result_urls = result_json.get("resultUrls", []) + if not result_urls: + return self._handle_error(f"❌ {tag} Aucune URL.", _batch_idx) + output_url = result_urls[0] + except Exception as e: + return self._handle_error(f"❌ {tag} Parsing error : {e}", _batch_idx) + + try: + img_resp = requests.get(output_url, timeout=60) + img_resp.raise_for_status() + pil_result = Image.open(io.BytesIO(img_resp.content)).convert("RGB") + image_np = np.array(pil_result).astype(np.float32) / 255.0 + image_tensor_out = torch.from_numpy(image_np)[None,] + cost_ms = result_data.get("costTime", 0) + info = ( + f"[Kie.ai] Model: {model_label}\n" + f"Resolution: {image_size} | Ratio: {aspect_ratio}\n" + f"Time: {cost_ms}ms | Total: {elapsed}s" + ) + print(f"🎉 {tag} Done!\n{info}") + return (image_tensor_out, info, "") + except Exception as e: + return self._handle_error(f"❌ {tag} Download failed: {e}", _batch_idx) + + # ───────────────────────────────────────────────────────────── + # Auto-install OpenCV (headless) + # ───────────────────────────────────────────────────────────── + @staticmethod + def _ensure_opencv() -> bool: + try: + import cv2 # noqa: F401 + return True + except ImportError: + print("📦 [FaceSwap] Installing required dependency...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "opencv-python-headless", "--quiet", + ]) + print("✅ [FaceSwap] Dependency installed successfully.") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [FaceSwap] Failed to install dependency: {e}") + return False + + # ───────────────────────────────────────────────────────────── + # Mask face(s) in image tensor with a black rectangle (YuNet) + # ───────────────────────────────────────────────────────────── + def _mask_face_in_tensor(self, img_tensor): + """ + Detects faces in the image 2 tensor and masks them + with a black square (YuNet via OpenCV). + Returns the modified tensor, or the original if OpenCV is unavailable. + """ + if not self._ensure_opencv(): + print("⚠️ [FaceSwap] OpenCV unavailable — image 2 will not be masked") + return img_tensor + + import cv2 + + try: + pil_img = tensor_to_pil(img_tensor) + img_rgb = np.array(pil_img.convert("RGB")) + img_bgr = img_rgb[:, :, ::-1].copy() + h, w = img_bgr.shape[:2] + + # Detection model — cached alongside the node to survive restarts + model_dir = os.path.join(os.path.dirname(__file__), ".yunet_cache") + os.makedirs(model_dir, exist_ok=True) + model_path = os.path.join(model_dir, "face_detection_yunet_2023mar.onnx") + + if not os.path.exists(model_path): + print("📥 [FaceSwap] Downloading detection model for python...") + _urllib_request.urlretrieve( + "https://github.com/opencv/opencv_zoo/raw/main/models/" + "face_detection_yunet/face_detection_yunet_2023mar.onnx", + model_path, + ) + print("✅ [FaceSwap] Detection model ready.") + + detector = cv2.FaceDetectorYN.create( + model_path, "", (w, h), + score_threshold=0.7, nms_threshold=0.3, top_k=5000, + ) + min_face = min(w, h) * 0.05 + faces = [] + + _, detections = detector.detect(img_bgr) + if detections is not None: + for det in detections: + fx, fy, fw, fh = ( + int(det[0]), int(det[1]), int(det[2]), int(det[3]) + ) + conf = float(det[-1]) + if fw < min_face or fh < min_face: + continue + faces.append((fx, fy, fw, fh)) + print(f" [FaceSwap] Face detected ✅") + + if not faces: + print("🔴 [FaceSwap] WARNING: No face detected in image 2 — face swap may fail!") + return img_tensor + + for (fx, fy, fw, fh) in faces: + pad_w = int(fw * 0.30) + pad_h = int(fh * 0.30) + x1 = max(0, fx - pad_w) + y1 = max(0, fy - pad_h) + x2 = min(w, fx + fw + pad_w) + y2 = min(h, fy + fh + pad_h) + cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (0, 0, 0), -1) + + img_rgb_out = img_bgr[:, :, ::-1].copy() + img_float = img_rgb_out.astype(np.float32) / 255.0 + return torch.from_numpy(img_float)[None,] + + except Exception as exc: + print(f"⚠️ [FaceSwap] Masking error: {exc} — using original image 2") + return img_tensor + + # ───────────────────────────────────────────────────────────── + # Aspect ratio auto-detection for Face Swap Automation + # ───────────────────────────────────────────────────────────── + _NB_ASPECT_RATIOS = { + "1:1": 1.0, + "2:3": 2/3, + "3:2": 3/2, + "3:4": 3/4, + "4:3": 4/3, + "4:5": 4/5, + "5:4": 5/4, + "9:16": 9/16, + "16:9": 16/9, + "21:9": 21/9, + } + + @staticmethod + def _detect_aspect_ratio(img_tensor) -> str: + """Return the Nano Banana ratio string closest to the actual image dimensions.""" + try: + # img_tensor shape: [B, H, W, C] (ComfyUI convention) + h = img_tensor.shape[1] + w = img_tensor.shape[2] + if h == 0 or w == 0: + return "1:1" + actual = w / h + best_key = min( + NanoBananaAIO._NB_ASPECT_RATIOS, + key=lambda k: abs(NanoBananaAIO._NB_ASPECT_RATIOS[k] - actual), + ) + return best_key + except Exception: + return "1:1" + + # ───────────────────────────────────────────────────────────── + # Automation Face Swap — main dispatcher + # ───────────────────────────────────────────────────────────── + def _run_face_swap_automation( + self, + provider, model, image_size, aspect_ratio, + batch_size, disable_safety, breast_refiner_enabled, + low_neck_enabled, + face_expression, + image_1, image_2, + gemini_api_key="", wavespeed_api_key="", kie_api_key="", + fal_api_key="", vertex_json_folder="", vertex_location="us-central1", + temperature=1.0, top_p=0.95, fal_safety_tolerance="4", + ): + if image_1 is None or image_2 is None: + return self._handle_error( + "❌ [Automation] Image 1 (reference face) " + "and Image 2 (face to swap) are both required." + ) + + if model not in ("Nano Banana Pro", "Nano Banana 2"): + model = "Nano Banana Pro" + print("⚠️ [Automation] Incompatible model → forced: Nano Banana Pro") + + is_nb2 = (model == "Nano Banana 2") + actual_model = _MODEL_MAP.get(model, "gemini-3-pro-image-preview") + + # Auto-detect aspect ratio from image_2 dimensions + auto_ratio = self._detect_aspect_ratio(image_2) + + print(f"\n{'═'*55}") + print("⚡ AUTOMATION FACE SWAP") + print(f" Provider : {provider}") + print(f" Model : {model}") + print(f" Aspect Ratio : {auto_ratio} (auto-detected from image 2)") + print(f" Batch size : {batch_size}") + print(f" Safety off : {disable_safety}") + print(f" Breast Refin.: {'ON ✅' if breast_refiner_enabled else 'OFF'}") + print(f" Low Neck : {'ON ✅' if low_neck_enabled else 'OFF'}") + print(f"{'═'*55}\n") + + # Step 1 : mask face in image_2 + print("🎭 [FaceSwap] Masking face in image 2...") + masked_image_2 = self._mask_face_in_tensor(image_2) + + # Step 2 : decode hidden prompt (never printed to console) + fs_prompt = base64.b64decode(_FACESWAP_PROMPT_B64).decode("utf-8") + if breast_refiner_enabled: + fs_prompt += "\n\n" + base64.b64decode(_BREAST_REFINER_B64).decode("utf-8") + if low_neck_enabled: + fs_prompt += "\n\nAdd a low neck" + + # Append facial expression instruction + _EXPRESSION_MAP = { + "Neutral": "neutral facial expression", + "Sensual": "sensual facial expression, intelse eyes look", + "Playful": "playful facial expression", + "Subtle smile": "subtle smile", + "Smile": "warm smile", + "Laugh": "she's laughing", + } + expression_text = _EXPRESSION_MAP.get(face_expression, "neutral facial expression") + fs_prompt += f"\n\n{expression_text}" + + image_tensors = [image_1, masked_image_2] + + # Safety: breast refiner / low neck content always requires filters OFF + if breast_refiner_enabled or low_neck_enabled or disable_safety: + safety_threshold = "OFF" + else: + safety_threshold = None + + print(f"🚀 [FaceSwap] Sending to {model} via {provider}...") + + # Step 3 : route to provider (auto_ratio replaces aspect_ratio everywhere) + if provider == "WAVESPEED": + return self._generate_wavespeed( + fs_prompt, image_tensors, image_size, "jpeg", + auto_ratio, batch_size=batch_size, + ws_api_key=wavespeed_api_key, is_nb2=is_nb2, + ) + + elif provider == "KIE": + return self._generate_kie( + fs_prompt, image_tensors, image_size, auto_ratio, + kie_api_key=kie_api_key, ws_api_key=wavespeed_api_key, + batch_size=batch_size, is_nb2=is_nb2, + ) + + elif provider == "FAL": + return self._generate_fal( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + batch_size = batch_size, + fal_api_key = fal_api_key, + is_nb2 = is_nb2, + safety_tolerance = fal_safety_tolerance, + enable_web_search = False, + ) + + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Automation] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + print(f"📁 [Vertex Automation] {len(_vj_files)} project(s) detected") + if batch_size > len(_vj_files): + print(f"⚠️ [Vertex Automation] batch_size={batch_size} > projects={len(_vj_files)} → batch reduced to {len(_vj_files)}") + batch_size = len(_vj_files) + # Rotation + _off = NanoBananaAIO._vertex_rotation_offset % len(_vj_files) + _vj_files = _vj_files[_off:] + _vj_files[:_off] + NanoBananaAIO._vertex_rotation_offset = (_off + batch_size) % len(_vj_files) + print(f"🔄 [Vertex Automation] Rotation offset={_off} → projects used : {[os.path.basename(f) for f in _vj_files[:batch_size]]}") + if is_nb2: + return self._generate_nb2_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + batch_size = batch_size, + disable_safety = disable_safety, + ) + return self._generate_vertex( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + top_p = top_p, + use_search = False, + system_instructions = None, + batch_size = batch_size, + vertex_json_files = _vj_files, + vertex_location = vertex_location, + model_name = actual_model, + safety_threshold = "BLOCK_NONE" if disable_safety else None, + ) + + else: # GOOGLE + if not gemini_api_key: + return self._handle_error( + "❌ [Automation] gemini_api_key missing pour GOOGLE." + ) + if is_nb2: + return self._generate_nb2_google( + prompt = fs_prompt, + image_tensors = image_tensors, + image_size = image_size, + aspect_ratio = auto_ratio, + temperature = temperature, + g_key = gemini_api_key, + batch_size = batch_size, + disable_safety = disable_safety, + ) + approach = self._detect_approach(gemini_api_key, "", "") + contents = [fs_prompt] + for i, t in enumerate(image_tensors, 1): + print(f"📷 [FaceSwap] Image {i} added to Google context...") + contents.append(tensor_to_pil(t)) + if batch_size == 1: + return self._generate_single_image( + actual_model, fs_prompt, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + else: + return self._generate_batch_parallel( + actual_model, fs_prompt, batch_size, False, approach, contents, + auto_ratio, image_size, temperature, top_p, None, + g_key=gemini_api_key, v_proj="", v_loc="", + safety_threshold=safety_threshold, + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Point d'entrée principal + # ───────────────────────────────────────────────────────────── + def _generate_video( + self, + provider = "GOOGLE", + prompt = "", + model = "Veo 3.1 Lite", + video_resolution = "1080p", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + gemini_api_key = "", + wavespeed_api_key = "", + kie_api_key = "", + fal_api_key = "", + fal_safety_tolerance = "4", + vertex_json_folder = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + video_reference = None, + ): + """Routes video generation to the correct provider.""" + all_known = set(_VIDEO_MODEL_MAP.keys()) | _KLING_MODELS | _SEEDANCE_MODELS + if model not in all_known: + return self._handle_error( + f"❌ [Video] Unknown video model: '{model}'.\n" + f"Available models: {sorted(all_known)}" + ) + + # ── Snap de resolution ──────────────────────────────────── + # Seedance : 4K not supported (480p / 720p / 1080p OK) + if model in _SEEDANCE_MODELS and video_resolution == "4K": + print(f"⚠️ [Video] Seedance 2.0 ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # 4K uniquement pour Kling 3.0 — les autres models snappent vers 1080p + elif model != "Kling 3.0" and video_resolution == "4K": + print(f"⚠️ [Video] {model} ne supporte pas 4K → snap vers 1080p") + video_resolution = "1080p" + # Autres models vidéo : pas de 480p + elif model not in _SEEDANCE_MODELS and video_resolution == "480p": + print(f"⚠️ [Video] {model} ne supporte pas 480p → snap vers 720p") + video_resolution = "720p" + + # ── Kling 2.6 — KIE ────────────────────────────────────── + if model == "Kling 2.6" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 2.6 / KIE.") + return self._generate_kling26_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 2.6 — FAL (Pro 1080p uniquement) ─────────────── + if model == "Kling 2.6" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 2.6 / FAL.") + return self._generate_kling26_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 Motion Control — KIE ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 Motion Control / KIE.") + return self._generate_kling_motion_control_kie( + prompt = prompt, + resolution = video_resolution, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 Motion Control — FAL ─────────────────────── + if model == "Kling 3.0 Motion Control" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 Motion Control / FAL.") + return self._generate_kling_motion_control_fal( + prompt = prompt, + resolution = video_resolution, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + + # ── Kling 3.0 — FAL (Standard 720p / Pro 1080p / 4K) ──────── + if model == "Kling 3.0" and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Kling 3.0 / FAL.") + return self._generate_kling30_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling 3.0 — KIE (Std 720p / Pro 1080p / 4K) ─────────────── + if model == "Kling 3.0" and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Kling 3.0 / KIE.") + return self._generate_kling30_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Kling — WaveSpeed (Kling 3.0, 2.6, Motion Control) ─── + if model in _KLING_MODELS: + if provider != "WAVESPEED": + return self._handle_error( + f"❌ [Video] {model} est disponible via WAVESPEED, KIE ou FAL " + "(Kling 3.0 : WAVESPEED/KIE/FAL — Kling 2.6 : WAVESPEED/KIE/FAL — " + "Motion Control : WAVESPEED/FAL).\n" + "→ Select WAVESPEED, KIE or FAL." + ) + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour Kling." + ) + if model == "Kling 3.0 Motion Control": + return self._generate_kling_motion_control_wavespeed( + prompt = prompt, + resolution = video_resolution, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + video_reference = video_reference, + ) + return self._generate_kling_wavespeed( + model = model, + prompt = prompt, + resolution = video_resolution, + duration = duration, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — WaveSpeed ────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error("❌ [Video] wavespeed_api_key missing for Seedance 2.0 / WaveSpeed.") + return self._generate_seedance_wavespeed( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — FAL ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "FAL": + if not fal_api_key: + return self._handle_error("❌ [Video] fal_api_key missing for Seedance 2.0 / FAL.") + return self._generate_seedance_fal( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — KIE ──────────────────────────────────── + if model in _SEEDANCE_MODELS and provider == "KIE": + if not kie_api_key: + return self._handle_error("❌ [Video] kie_api_key missing for Seedance 2.0 / KIE.") + return self._generate_seedance_kie( + prompt = prompt, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + + # ── Seedance 2.0 — Provider not supported ────────────────── + if model in _SEEDANCE_MODELS: + return self._handle_error( + f"❌ [Video] Seedance 2.0 est disponible sur WAVESPEED, FAL et KIE uniquement.\n" + f"→ Select WAVESPEED, FAL or KIE." + ) + + if provider == "GOOGLE": + if not gemini_api_key: + return self._handle_error( + "❌ [Video] gemini_api_key missing pour le provider GOOGLE." + ) + return self._generate_veo_google( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP[model], + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + g_key = gemini_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "VERTEX": + if not vertex_json_folder: + return self._handle_error( + "❌ [Video] vertex_json_folder missing for VERTEX provider." + ) + try: + _vj_files_vid = _load_vertex_json_folder(vertex_json_folder) + except Exception as _e: + return self._handle_error(str(_e)) + return self._generate_veo_vertex( + prompt = prompt, + model_id = _VIDEO_MODEL_MAP_VERTEX.get(model, _VIDEO_MODEL_MAP[model]), + aspect_ratio = aspect_ratio, + duration = duration, + generate_audio = generate_audio, + vertex_json_path = _vj_files_vid[0], + vertex_location = vertex_location, + vertex_gcs_bucket = vertex_gcs_bucket, + image_tensors = image_tensors or [], + ) + elif provider == "WAVESPEED": + if not wavespeed_api_key: + return self._handle_error( + "❌ [Video] wavespeed_api_key missing pour le provider WAVESPEED." + ) + if model not in _VIDEO_MODEL_MAP_WAVESPEED: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur WaveSpeed.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_WAVESPEED.keys())}" + ) + return self._generate_veo_wavespeed( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "KIE": + if not kie_api_key: + return self._handle_error( + "❌ [Video] kie_api_key missing pour le provider KIE." + ) + if model not in _VIDEO_MODEL_MAP_KIE: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur Kie.ai.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_KIE.keys())}" + ) + return self._generate_veo_kie( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + kie_api_key = kie_api_key, + ws_api_key = wavespeed_api_key, + image_tensors = image_tensors or [], + ) + elif provider == "FAL": + if not fal_api_key: + return self._handle_error( + "❌ [Video] fal_api_key missing pour le provider FAL." + ) + if model not in _VIDEO_MODEL_MAP_FAL: + return self._handle_error( + f"❌ [Video] Le model '{model}' n'est pas disponible sur FAL.\n" + f"Available models: {list(_VIDEO_MODEL_MAP_FAL.keys())}" + ) + return self._generate_veo_fal( + prompt = prompt, + model = model, + aspect_ratio = aspect_ratio, + duration = duration, + resolution = video_resolution, + generate_audio = generate_audio, + fal_api_key = fal_api_key, + safety_tolerance = fal_safety_tolerance, + image_tensors = image_tensors or [], + ) + else: + return self._handle_error( + f"❌ [Video] Provider '{provider}' does not support Veo video generation.\n" + "→ Select GOOGLE, VERTEX, WAVESPEED, KIE or FAL to use Veo models." + ) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Google AI Studio (Gemini API) + # ───────────────────────────────────────────────────────────── + def _generate_veo_google( + self, + prompt = "", + model_id = "veo-3.0-generate-preview", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + g_key = "", + image_tensors = None, + ): + tag = "[Veo Google]" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + try: + client = genai.Client(api_key=g_key) + except Exception as e: + return self._handle_error(f"❌ {tag} Unable to create Google client: {e}") + + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s out of API range (4-8s), adjusted to {duration_clamped}s") + + config = types.GenerateVideosConfig( + aspect_ratio = aspect_ratio, + duration_seconds = duration_clamped, + generate_audio = generate_audio, + ) + + try: + if image_tensors: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + buf.seek(0) + src_image = types.Image( + image_bytes = buf.getvalue(), + mime_type = "image/png", + ) + print(f"🖼️ {tag} Image-to-video mode (image_1 used as reference)") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + image = src_image, + config = config, + ) + else: + print(f"✏️ {tag} Mode text-to-video") + operation = client.models.generate_videos( + model = model_id, + prompt = prompt, + config = config, + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Error starting generation: {type(e).__name__}: {e}" + ) + + print(f"⏳ {tag} Generating (may take several minutes)...") + elapsed = 0 + while elapsed < _VIDEO_TIMEOUT_S: + try: + if operation.done: + break + except Exception: + pass + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + operation = client.operations.get(operation) + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting...") + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + try: + # Veo 3.0 → .result | Veo 3.1 → .response + try: + generated = operation.result.generated_videos + except Exception: + generated = operation.response.generated_videos + + if not generated: + return self._handle_error(f"❌ {tag} No video returned by API.") + + generated_video = generated[0] + # CRITIQUE : files.download() OBLIGATOIRE avant d'accéder à video_bytes + client.files.download(file=generated_video.video) + video_bytes = generated_video.video.video_bytes + + if not video_bytes: + return self._handle_error( + f"❌ {tag} video_bytes empty after download — check Files API permissions." + ) + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to read video response: {type(e).__name__}: {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Vertex AI + # ───────────────────────────────────────────────────────────── + def _generate_veo_vertex( + self, + prompt = "", + model_id = "veo-3.1-lite-generate-001", + aspect_ratio = "16:9", + duration = 8, + generate_audio = True, + vertex_json_path = "", + vertex_location = "us-central1", + vertex_gcs_bucket = "", + image_tensors = None, + ): + """Vertex AI video generation via REST (predictLongRunning + fetchPredictOperation).""" + tag = "[Veo Vertex]" + location = vertex_location or "us-central1" + print(f"🎬 {tag} Starting — model={model_id} | ratio={aspect_ratio} | duration={duration}s") + + # ── 1. Credentials & token ──────────────────────────────── + try: + import google.auth.transport.requests as _gtr + credentials, project_id = _load_vertex_credentials(vertex_json_path) + credentials.refresh(_gtr.Request()) + token = credentials.token + print(f"🌐 {tag} Projet={project_id} | location={location}") + except Exception as e: + return self._handle_error(f"❌ {tag} Invalid credentials: {e}") + + # ── 2. GCS bucket (optionnel — Vertex auto-crée gs://veo-videos-{project}) ── + # Défense contre True/None/bool que ComfyUI peut envoyer pour un input vide + _raw_gcs = vertex_gcs_bucket if isinstance(vertex_gcs_bucket, str) else "" + gcs_bucket = _raw_gcs.strip() + print(f"📦 {tag} vertex_gcs_bucket received: {repr(vertex_gcs_bucket)} → gcs_bucket={repr(gcs_bucket)}") + + # ── 3. Construction de la requête ───────────────────────── + base = f"https://{location}-aiplatform.googleapis.com/v1" + model_path = ( + f"projects/{project_id}/locations/{location}" + f"/publishers/google/models/{model_id}" + ) + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json; charset=utf-8", + "x-goog-user-project": project_id, + } + + instance: dict = {"prompt": prompt} + if image_tensors: + try: + from ..utils.image_utils import tensor_to_pil + pil_img = tensor_to_pil(image_tensors[0]) + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + instance["image"] = { + "bytesBase64Encoded": base64.b64encode(buf.getvalue()).decode(), + "mimeType": "image/png", + } + print(f"🖼️ {tag} Mode image-to-video") + except Exception as e: + print(f"⚠️ {tag} Unable to encode image: {e}") + + params: dict = { + "sampleCount": 1, + "durationSeconds": duration, + "aspectRatio": aspect_ratio, + "generateAudio": generate_audio, + } + # N'ajouter storageUri que si c'est un vrai URI gs:// — Vertex auto-bucket sinon + if gcs_bucket.startswith("gs://"): + params["storageUri"] = gcs_bucket + print(f"📦 {tag} storageUri sent: {gcs_bucket}") + else: + print(f"📦 {tag} storageUri omis — Vertex utilisera son bucket auto") + + payload = { + "instances": [instance], + "parameters": params, + } + + # ── 4. Lancement de l'opération longue ──────────────────── + try: + resp = requests.post( + f"{base}/{model_path}:predictLongRunning", + headers = headers, + json = payload, + timeout = 30, + ) + resp.raise_for_status() + operation_name = resp.json()["name"] + print(f"✅ {tag} Operation started: {operation_name}") + except Exception as e: + return self._handle_error(f"❌ {tag} Launch error : {e}") + + # ── 5. Polling fetchPredictOperation ────────────────────── + print(f"⏳ {tag} Generating...") + elapsed = 0 + result = None + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + fetch = requests.post( + f"{base}/{model_path}:fetchPredictOperation", + headers = headers, + json = {"operationName": operation_name}, + timeout = 30, + ) + data = fetch.json() + status = "✅ done" if data.get("done") else "⏳ pending" + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] {status}") + if data.get("done"): + result = data + break + except Exception as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 6. Parsing de la réponse ────────────────────────────── + try: + response_body = result.get("response", {}) + videos = ( + response_body.get("videos") + or response_body.get("generatedSamples") + or [] + ) + if not videos: + return self._handle_error( + f"❌ {tag} No video in response.\n" + f"Full response: {result}" + ) + video_entry = videos[0] + # Log la structure pour debug futur + print(f"📼 {tag} Structure video_entry : { {k: (v[:40]+'…' if isinstance(v,str) and len(v)>40 else v) for k,v in video_entry.items()} }") + + # Cas 1 : vidéo retournée en base64 directement (sans storageUri) + b64 = ( + video_entry.get("bytesBase64Encoded") + or video_entry.get("video", {}).get("bytesBase64Encoded", "") + ) + if b64: + video_bytes = base64.b64decode(b64) + print(f"✅ {tag} Video decoded from base64 ({len(video_bytes)} bytes).") + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # Cas 2 : vidéo stockée dans GCS + gcs_uri = ( + video_entry.get("gcsUri") + or video_entry.get("video", {}).get("gcsUri", "") + ) + if not gcs_uri: + return self._handle_error( + f"❌ {tag} Neither base64 nor gcsUri in response.\n" + f"video_entry = {video_entry}" + ) + print(f"📼 {tag} GCS video: {gcs_uri}") + except Exception as e: + return self._handle_error(f"❌ {tag} Response read : {e}") + + # ── 7. Download depuis GCS (Storage REST API) ─────── + try: + gcs_path = gcs_uri.removeprefix("gs://") + bucket_name, _, object_name = gcs_path.partition("/") + encoded_obj = requests.utils.quote(object_name, safe="") + dl_url = ( + f"https://storage.googleapis.com/storage/v1/b" + f"/{bucket_name}/o/{encoded_obj}?alt=media" + ) + dl_resp = requests.get( + dl_url, + headers = {"Authorization": f"Bearer {token}"}, + timeout = 120, + ) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded from GCS ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error( + f"❌ {tag} Unable to download from GCS ({gcs_uri}): {e}" + ) + + return self._finalize_video(video_bytes, tag, model_id, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed Kling (Standard / Pro) + # ───────────────────────────────────────────────────────────── + def _generate_kling_wavespeed( + self, + model = "Kling 3.0", + prompt = "", + resolution = "720p", + duration = 5, + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + # 720p → Standard, 1080p → Pro (fallback sur Standard) + model_map = _KLING_WS_URL_MAP.get(model, _KLING_WS_URL_MAP["Kling 3.0"]) + slug = model_map.get(resolution, model_map["720p"]) + variant = "4K" if resolution == "4K" else ("Pro" if resolution == "1080p" else "Standard") + url = f"{WAVESPEED_BASE_URL}/{slug}" + tag = f"[WaveSpeed {model} {variant}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Kling 2.6 n'accepte que 5 ou 10s ; Kling 3.0 accepte 3-15s + if model == "Kling 2.6": + dur = 10 if int(duration) > 7 else 5 + else: + dur = max(3, min(15, int(duration))) + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — text-to-video mode.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "cfg_scale": 0.5, + "shot_type": "customize", + "element_list": [], + "multi_prompt": [], + "sound": generate_audio, + } + if image_url: + payload["image"] = image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", dur) + + # ───────────────────────────────────────────────────────────── + # Kling 3.0 Motion Control — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _video_to_public_url(self, video_ref: str, ws_api_key: str) -> str | None: + """Uploads a local video to WaveSpeed (multipart) and returns the public URL. + If video_ref is already a URL (http/https), it is returned as-is.""" + if not video_ref: + return None + video_ref = video_ref.strip() + if video_ref.startswith(("http://", "https://")): + return video_ref + if not os.path.isfile(video_ref): + print(f"⚠️ [MotionControl] Video file not found: {video_ref}") + return None + ext = os.path.splitext(video_ref)[1].lower() or ".mp4" + mime = "video/mp4" if ext == ".mp4" else f"video/{ext.lstrip('.')}" + filename = os.path.basename(video_ref) + try: + with open(video_ref, "rb") as f: + resp = requests.post( + WAVESPEED_UPLOAD_URL, + headers={"Authorization": f"Bearer {ws_api_key}"}, + files={"file": (filename, f, mime)}, + timeout=120, + ) + resp.raise_for_status() + data = resp.json() + url = (data.get("data") or {}).get("download_url") or (data.get("data") or {}).get("url") + return url + except Exception as e: + print(f"⚠️ [MotionControl] Error uploading video: {e}") + return None + + def _generate_kling_motion_control_wavespeed( + self, + prompt = "", + resolution = "720p", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + variant = "Pro" if resolution == "1080p" else "Std" + tag = f"[WaveSpeed Kling 3.0 Motion Control {variant}]" + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + slug_map = _KLING_WS_URL_MAP["Kling 3.0 Motion Control"] + slug = slug_map.get(resolution, slug_map["720p"]) + url = f"{WAVESPEED_BASE_URL}/{slug}" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload de la vidéo de référence ──────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "video": video_url, + "character_orientation": "video", + "element_list": [], + "keep_original_sound": True, + "shot_type": "customize", + } + if image_url: + payload["image"] = image_url + + # ── 4. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 5. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_out_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — WaveSpeed (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_wavespeed( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + slug = _VIDEO_MODEL_MAP_WAVESPEED[model] + tag = f"[WaveSpeed {model}]" + url = f"{WAVESPEED_BASE_URL}/google/{slug}/image-to-video" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Starting — ratio={aspect_ratio} | duration={duration}s | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + image_url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed, text-to-video mode.") + + # ── 2. Soumission ───────────────────────────────────────── + duration_clamped = max(4, min(8, int(duration))) + if duration_clamped != duration: + print(f"⚠️ {tag} duration {duration}s adjusted to {duration_clamped}s (range 4-8)") + + payload = { + "aspect_ratio": aspect_ratio, + "duration": duration_clamped, + "generate_audio": generate_audio, + "prompt": prompt, + "resolution": resolution, + } + if image_url: + payload["image"] = image_url + + try: + submit_resp = requests.post(url, json=payload, headers=headers, timeout=30) + submit_resp.raise_for_status() + submit_data = submit_resp.json() + task_id = (submit_data.get("data") or {}).get("id") or submit_data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {submit_data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 3. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get(poll_url, headers={"Authorization": f"Bearer {ws_api_key}"}, timeout=15) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, slug, aspect_ratio, duration_clamped) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kie.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + def _generate_veo_kie( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + kie_model = _VIDEO_MODEL_MAP_KIE[model] + tag = f"[Kie.ai {model}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + print(f"🎬 {tag} Initialisation — ratio={aspect_ratio} | resolution={resolution}") + if not generate_audio: + print(f"ℹ️ {tag} generate_audio=False ignored — Kie.ai always includes audio.") + + # ── 1. Upload des images de référence (optionnel) ───────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Déterminer le generationType ─────────────────────── + if image_urls: + generation_type = "FIRST_AND_LAST_FRAMES_2_VIDEO" + else: + generation_type = "TEXT_2_VIDEO" + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "prompt": prompt, + "model": kie_model, + "generationType": generation_type, + "aspect_ratio": aspect_ratio, + "resolution": resolution, + "enableTranslation": True, + } + if image_urls: + payload["imageUrls"] = image_urls + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_VEO_GENERATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + if data.get("code") != 200: + return self._handle_error(f"❌ {tag} Submission rejected: {data.get('msg')}") + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId in response: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + _debug_logged = False + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_VEO_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + # Kie.ai Veo : successFlag 1 = terminé, errorCode/errorMessage = échec + error_code = result_data.get("errorCode") + error_msg = result_data.get("errorMessage") + if error_code or error_msg: + return self._handle_error( + f"❌ {tag} Generation failed: [{error_code}] {error_msg}" + ) + if result_data.get("successFlag") == 1 or result_data.get("completeTime"): + print(f"✅ {tag} Task done! ({elapsed}s)") + break + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] waiting (successFlag=0)...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Récupération de l'URL vidéo ──────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ "response" = URL directe (Kie.ai Veo) + raw_response = result_data.get("response") + if isinstance(raw_response, str) and raw_response.startswith("http"): + video_url = raw_response + # Cas 2 : "response" est un JSON sérialisé + elif isinstance(raw_response, str): + try: + parsed = _json.loads(raw_response) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + # Cas 3 : "response" est déjà un dict + elif isinstance(raw_response, dict): + video_url = ( + raw_response.get("videoUrl") + or raw_response.get("video_url") + or (raw_response.get("resultUrls") or [None])[0] + ) + # Cas 4 : videoUrl ou resultJson au niveau de data (fallback) + if not video_url: + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download de la vidéo ───────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Video download error : {e}") + + return self._finalize_video(video_bytes, tag, kie_model, aspect_ratio, duration) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_kie( + self, + prompt = "", + resolution = "720p", + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + video_reference = None, + ): + mode = "1080p" if resolution == "1080p" else "720p" + tag = f"[Kie.ai Kling 3.0 Motion Control {mode}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation — mode={mode}") + + # ── 1. Upload image de référence (optionnel) ────────────── + input_urls = [] + if image_tensors: + url = self._tensor_to_public_url(image_tensors[0], idx=1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + input_urls.append(url) + print(f"🖼️ {tag} Image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload failed — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + video_url = self._video_to_public_url(video_reference, ws_api_key=ws_api_key) + if not video_url: + return self._handle_error( + f"❌ {tag} Unable to upload reference video." + ) + print(f"🎞️ {tag} Reference video → {video_url[:60]}…") + + # ── 3. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-3.0/motion-control", + "input": { + "prompt": prompt, + "input_urls": input_urls, + "video_urls": [video_url], + "mode": mode, + "character_orientation": "video", + "background_source": "input_video", + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 4. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_MOTION_CONTROL_TIMEOUT_S}s)...") + while elapsed < _MOTION_CONTROL_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_MOTION_CONTROL_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_MOTION_CONTROL_TIMEOUT_S}s.") + + # ── 5. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_out = None + video_out = result_data.get("videoUrl") or result_data.get("video_url") + if not video_out: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_out = (result_json.get("resultUrls") or [None])[0] + if not video_out: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_out = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_out = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_out = raw.get("videoUrl") or raw.get("video_url") + if not video_out: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_out[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 6. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_out, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/motion-control", "16:9", 0) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = "[Kie.ai Kling 2.6]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 5 ou 10s uniquement ────────────────────────── + dur = 10 if int(duration) > 7 else 5 + + print(f"🎬 {tag} Initializing — duration={dur}s | audio={generate_audio}") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_urls = [] + for idx, tensor in enumerate(image_tensors or []): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + print(f"🖼️ {tag} Image {idx+1} uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + break # Kie.ai Kling 2.6 accepte max 1 image + + # ── 2. Soumission ───────────────────────────────────────── + payload = { + "model": "kling-2.6/image-to-video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": generate_audio, + "duration": str(dur), + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = None + # Cas 1 : champ direct + video_url = result_data.get("videoUrl") or result_data.get("video_url") + # Cas 2 : resultJson → resultUrls + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + # Cas 3 : response field (comme Veo) + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-2.6/image-to-video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 — Kie.ai + # Endpoint unique : model="kling-3.0/video" + # Mode (std / pro) pilotés par le paramètre "mode" du payload. + # Jusqu'à 2 images : [0]=première frame, [1]=dernière frame. + # ───────────────────────────────────────────────────────────── + def _generate_kling30_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + # 4K = "4K" | pro = 1080p | std = 720p + mode_api = "4K" if resolution == "4K" else ("pro" if resolution == "1080p" else "std") + tag = f"[Kie.ai Kling 3.0 {'Pro' if mode_api == 'pro' else 'Std'}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # ── Durée : 3 → 15s, entier ────────────────────────────── + dur = max(3, min(15, int(duration))) + + print(f"🎬 {tag} Starting — duration={dur}s | mode={mode_api} | " + f"ratio={aspect_ratio} | audio={generate_audio}") + + # ── 1. Upload images de référence (max 2 : start + end) ── + # Kling 3.0 accepte une image de début (index 0) et une + # image de fin (index 1). Les suivantes sont ignoredes. + image_urls = [] + tensors = list(image_tensors or []) + if len(tensors) > 2: + print(f"⚠️ {tag} {len(tensors)} images fournies — seules les 2 " + f"first (start + end) will be used.") + tensors = tensors[:2] + for idx, tensor in enumerate(tensors): + url = self._tensor_to_public_url(tensor, idx=idx + 1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + image_urls.append(url) + role = "start" if idx == 0 else "end" + print(f"🖼️ {tag} Image {role} ({idx+1}/{len(tensors)}) uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload {idx+1} failed, skipped.") + + # ── 2. Payload ─────────────────────────────────────────── + payload = { + "model": "kling-3.0/video", + "input": { + "prompt": prompt, + "image_urls": image_urls, + "sound": bool(generate_audio), + "duration": str(dur), + "aspect_ratio": aspect_ratio, + "mode": mode_api, + "multi_shots": False, + }, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ─────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ──────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ──────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, "kling-3.0/video", aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — WaveSpeed + # ───────────────────────────────────────────────────────────── + def _generate_seedance_wavespeed( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + ws_api_key = "", + image_tensors = None, + ): + url = f"{WAVESPEED_BASE_URL}/{WS_SEEDANCE20_SLUG}" + tag = f"[WaveSpeed Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {ws_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio}") + + # ── 1. Upload image de début (obligatoire) ──────────────── + tensors = list(image_tensors or []) + image_url = None + last_image_url = None + + if tensors: + image_url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key) + if image_url: + print(f"🖼️ {tag} Start image uploaded → {image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + else: + print(f"⚠️ {tag} Seedance 2.0 est image-to-video — aucune image fournie.") + + if len(tensors) >= 2: + last_image_url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key) + if last_image_url: + print(f"🖼️ {tag} End image uploaded → {last_image_url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + payload: dict = { + "prompt": prompt, + "duration": dur, + "resolution": resolution, + } + # Aspect ratio (facultatif — s'adapte à l'image si non spécifié) + if aspect_ratio in ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9"): + payload["aspect_ratio"] = aspect_ratio + if image_url: + payload["image"] = image_url + if last_image_url: + payload["last_image"] = last_image_url + + # ── 3. Soumission ───────────────────────────────────────── + try: + resp = requests.post(url, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + task_id = (data.get("data") or {}).get("id") or data.get("id") + if not task_id: + return self._handle_error(f"❌ {tag} Submission failed: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + # ── 4. Polling ──────────────────────────────────────────── + poll_url = WAVESPEED_POLL_URL.format(task_id=task_id) + elapsed = 0 + poll_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = requests.get( + poll_url, + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + status = poll_data.get("data", {}).get("status", "") + if status == "completed": + outputs = poll_data.get("data", {}).get("outputs", []) + if not outputs: + return self._handle_error(f"❌ {tag} Completed but no video output.") + video_url = outputs[0] + print(f"✅ {tag} Video ready! ({elapsed}s)") + break + elif status == "failed": + error_msg = poll_data.get("data", {}).get("error", "Error inconnue") + return self._handle_error(f"❌ {tag} Generation failed: {error_msg}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] status={status!r}...") + else: + try: + requests.delete( + WAVESPEED_CANCEL_URL.format(task_id=task_id), + headers={"Authorization": f"Bearer {ws_api_key}"}, + timeout=10, + ) + except Exception: + pass + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, WS_SEEDANCE20_SLUG, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = f"[Fal.ai Seedance 2.0 {resolution}]" + endpoint = FAL_SEEDANCE20_ENDPOINT + + # Durée : "4"–"15" (string) ou "auto" + dur = max(4, min(15, int(duration))) + fal_duration = str(dur) + + # Aspect ratio : snap si hors liste FAL + _SEEDANCE_FAL_AR = {"auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"} + _SEEDANCE_FAL_AR_FALLBACK = { + "2:3": "3:4", "3:2": "4:3", "4:5": "3:4", "5:4": "4:3", + } + if aspect_ratio not in _SEEDANCE_FAL_AR: + fallback = _SEEDANCE_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── Upload image de début (optionnel) ───────────────────── + image_url = None + if tensors: + try: + image_url = _tensor_to_fal_url(tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Start image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload start failed: {e}") + + # ── Upload image de fin (optionnel) ─────────────────────── + end_image_url = None + if len(tensors) >= 2: + try: + end_image_url = _tensor_to_fal_url(tensors[1], fal_client, tag=tag, idx=2) + print(f"🖼️ {tag} End image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload end failed: {e}") + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "resolution": resolution, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "generate_audio": generate_audio, + } + if image_url: + arguments["image_url"] = image_url + if end_image_url: + arguments["end_image_url"] = end_image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + print(f"🚀 {tag} Submitting...") + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Seedance 2.0 — Kie.ai + # ───────────────────────────────────────────────────────────── + def _generate_seedance_kie( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + kie_api_key = "", + ws_api_key = "", + image_tensors = None, + ): + tag = f"[Kie.ai Seedance 2.0 {resolution}]" + headers = { + "Authorization": f"Bearer {kie_api_key}", + "Content-Type": "application/json", + } + + # Durée : 4–15s + dur = max(4, min(15, int(duration))) + print(f"🎬 {tag} Starting — duration={dur}s | resolution={resolution} | ratio={aspect_ratio} | audio={generate_audio}") + + tensors = list(image_tensors or []) + + # ── 1. Upload images de référence ───────────────────────── + first_frame_url = None + last_frame_url = None + + if tensors: + url = self._tensor_to_public_url(tensors[0], idx=1, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + first_frame_url = url + print(f"🖼️ {tag} Start image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload start failed.") + + if len(tensors) >= 2: + url = self._tensor_to_public_url(tensors[1], idx=2, ws_api_key=ws_api_key, kie_api_key=kie_api_key) + if url: + last_frame_url = url + print(f"🖼️ {tag} End image uploaded → {url[:60]}…") + else: + print(f"⚠️ {tag} Image upload end failed, skipped.") + + # ── 2. Payload ──────────────────────────────────────────── + input_params = { + "prompt": prompt, + "generate_audio": bool(generate_audio), + "resolution": resolution, + "aspect_ratio": aspect_ratio, + "duration": int(dur), + } + if first_frame_url: + input_params["first_frame_url"] = first_frame_url + if last_frame_url: + input_params["last_frame_url"] = last_frame_url + + payload = { + "model": KIE_SEEDANCE20_MODEL, + "input": input_params, + } + print(f"🚀 {tag} Submitting...") + + # Option B: session locale par batch (evite stale connections du pool global) + # Option C: jitter 0-0.5s avant POST en batch (evite burst simultane) + _local_kie = _make_kie_session() + if _batch_idx is not None: + import random as _random_jitter + time.sleep(_random_jitter.uniform(0, 0.5)) + try: + resp = _local_kie.post(KIE_CREATE_URL, json=payload, headers=headers, timeout=30) + resp.raise_for_status() + data = resp.json() + except requests.RequestException as e: + return self._handle_error(f"❌ {tag} Submission error : {e}") + + if data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Submission rejected: {data.get('msg', 'unknown error')}" + ) + task_id = data.get("data", {}).get("taskId") + if not task_id: + return self._handle_error(f"❌ {tag} No taskId: {data}") + print(f"🔖 {tag} Task ID : {task_id}") + + # ── 3. Polling ──────────────────────────────────────────── + elapsed = 0 + result_data = {} + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(_VIDEO_POLL_DELAY) + elapsed += _VIDEO_POLL_DELAY + try: + poll_resp = _local_kie.get( + KIE_POLL_URL, params={"taskId": task_id}, + headers=headers, timeout=15, + ) + poll_resp.raise_for_status() + poll_data = poll_resp.json() + except requests.RequestException as e: + print(f"⚠️ {tag} Polling error ({elapsed}s) : {e}") + continue + + if poll_data.get("code") != 200: + return self._handle_error( + f"❌ {tag} Poll error: {poll_data.get('msg')}" + ) + result_data = poll_data.get("data", {}) + state = result_data.get("state", "") + if state == "success": + print(f"✅ {tag} Task done! ({elapsed}s)") + break + elif state in ("fail", "failed", "error"): + return self._handle_error( + f"❌ {tag} Failed: {result_data.get('failMsg', '?')}" + ) + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] state={state!r}...") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + # ── 4. Récupération URL vidéo ───────────────────────────── + try: + import json as _json + video_url = result_data.get("videoUrl") or result_data.get("video_url") + if not video_url: + result_json = _json.loads(result_data.get("resultJson", "{}")) + video_url = (result_json.get("resultUrls") or [None])[0] + if not video_url: + raw = result_data.get("response") + if isinstance(raw, str) and raw.startswith("http"): + video_url = raw + elif isinstance(raw, str): + try: + parsed = _json.loads(raw) + video_url = ( + parsed.get("videoUrl") + or parsed.get("video_url") + or (parsed.get("resultUrls") or [None])[0] + ) + except Exception: + pass + elif isinstance(raw, dict): + video_url = raw.get("videoUrl") or raw.get("video_url") + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\ndata={result_data}" + ) + print(f"🎬 {tag} URL : {video_url[:80]}…") + except Exception as e: + return self._handle_error(f"❌ {tag} Response parsing : {e}") + + # ── 5. Download ───────────────────────────────────── + try: + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, KIE_SEEDANCE20_MODEL, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Fal.ai (Veo 3.1 / Fast / Lite) + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 2.6 Pro — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling26_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + tag = "[Fal.ai Kling 2.6 Pro]" + + # ── Résolution : FAL n'a que Pro (1080p) ────────────────── + if resolution != "1080p": + print(f"⚠️ {tag} Resolution {resolution!r} not available on FAL — " + f"utilisation de 1080p (Pro uniquement).") + + # ── Durée : 5 ou 10s uniquement ─────────────────────────── + dur = 10 if int(duration) > 7 else 5 + fal_duration = str(dur) # API attend "5" ou "10" + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING26_FAL_AR: + fallback = _KLING26_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + endpoint = FAL_KLING26_I2V_ENDPOINT if has_image else FAL_KLING26_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + endpoint = FAL_KLING26_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 (Standard 720p / Pro 1080p) — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling30_fal( + self, + prompt = "", + aspect_ratio = "16:9", + duration = 5, + resolution = "720p", + generate_audio = True, + fal_api_key = "", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + # ── Tag et endpoint selon resolution ────────────────────── + if resolution == "4K": + tag = "[Fal.ai Kling 3.0 4K]" + elif resolution == "1080p": + tag = "[Fal.ai Kling 3.0 Pro]" + else: + tag = "[Fal.ai Kling 3.0 Standard]" + + # ── Durée : 3–15s, chaîne ───────────────────────────────── + dur = max(_VIDEO_DURATION_MIN, min(_VIDEO_DURATION_MAX, int(duration))) + fal_duration = str(dur) + + # ── Aspect ratio : snap si hors liste ───────────────────── + if aspect_ratio not in _KLING30_FAL_AR: + fallback = _KLING30_FAL_AR_FALLBACK.get(aspect_ratio, "16:9") + print(f"⚠️ {tag} Aspect ratio {aspect_ratio!r} not supported → fallback {fallback!r}") + aspect_ratio = fallback + + has_image = bool(image_tensors) + if resolution == "4K": + endpoint = FAL_KLING30_4K_I2V_ENDPOINT if has_image else FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_I2V_ENDPOINT if has_image else FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_I2V_ENDPOINT if has_image else FAL_KLING30_STD_T2V_ENDPOINT + mode = "img2vid" if has_image else "txt2vid" + + print(f"🎬 {tag} [{mode}] ratio={aspect_ratio} | duration={dur}s | audio={generate_audio}") + + # ── Upload image (optionnel) ────────────────────────────── + image_url = None + if has_image: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + if resolution == "4K": + endpoint = FAL_KLING30_4K_T2V_ENDPOINT + elif resolution == "1080p": + endpoint = FAL_KLING30_PRO_T2V_ENDPOINT + else: + endpoint = FAL_KLING30_STD_T2V_ENDPOINT + mode = "txt2vid" + + # ── Payload ─────────────────────────────────────────────── + arguments = { + "prompt": prompt, + "duration": fal_duration, + "aspect_ratio": aspect_ratio, + "negative_prompt": "blur, distort, and low quality", + "generate_audio": generate_audio, + "cfg_scale": 0.5, + } + if image_url: + arguments["start_image_url"] = image_url + + # ── Subscribe ───────────────────────────────────────────── + _t0 = _time.time() + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + + # ── Download ──────────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url[:80]}…") + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Kling 3.0 Motion Control — Fal.ai + # ───────────────────────────────────────────────────────────── + def _generate_kling_motion_control_fal( + self, + prompt = "", + resolution = "720p", + fal_api_key = "", + image_tensors = None, + video_reference = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + import time as _time + os.environ["FAL_KEY"] = fal_api_key + + is_pro = (resolution == "1080p") + tag = f"[Fal.ai Kling 3.0 Motion Control {'Pro' if is_pro else 'Standard'}]" + endpoint = FAL_KLING30_PRO_MC_ENDPOINT if is_pro else FAL_KLING30_STD_MC_ENDPOINT + + if not video_reference: + return self._handle_error( + f"❌ {tag} video_reference missing.\n" + "→ Connect a reference video to the 'video_reference' input." + ) + + print(f"🎬 {tag} Initialisation") + + # ── 1. Upload image de référence (optionnel) ────────────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + print(f"🖼️ {tag} Image uploaded") + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — will be skipped.") + + # ── 2. Upload vidéo de référence ────────────────────────── + print(f"🎞️ {tag} Uploading reference video...") + try: + with open(video_reference, "rb") as f: + video_bytes_ref = f.read() + ext = os.path.splitext(video_reference)[1].lower() + mime = "video/mp4" if ext in (".mp4", ".m4v") else "video/webm" if ext == ".webm" else "video/mp4" + # Tentative 1 : upload vers FAL CDN + try: + video_url = fal_client.upload(video_bytes_ref, content_type=mime) + print(f"🎞️ {tag} Reference video uploaded → {video_url[:60]}…") + except Exception as upload_err: + # Fallback base64 data URI (FAL l'accepte nativement) + print(f"⚠️ {tag} FAL upload failed ({type(upload_err).__name__}) " + f"→ fallback base64 data URI ({len(video_bytes_ref)//1024} kB)") + video_url = f"data:{mime};base64,{base64.b64encode(video_bytes_ref).decode('ascii')}" + print(f"🎞️ {tag} Video encoded as base64.") + except Exception as e: + return self._handle_error(f"❌ {tag} Reference video read error : {e}") + + # ── 3. Payload ──────────────────────────────────────────── + arguments = { + "prompt": prompt, + "video_url": video_url, + "keep_original_sound": True, + "character_orientation": "video", + } + if image_url: + arguments["image_url"] = image_url + + # ── 4. Subscribe ────────────────────────────────────────── + import threading as _threading + + _t0 = _time.time() + _stop_log = _threading.Event() + _LOG_INTERVAL = 30 # secondes entre chaque ligne heartbeat + + def _progress_logger(): + """Affiche un heartbeat toutes les _LOG_INTERVAL secondes.""" + while not _stop_log.wait(_LOG_INTERVAL): + elapsed_now = int(_time.time() - _t0) + print(f" {tag} [{elapsed_now}s] Generating...") + + _last_log_t = [0.0] + + def _on_update(update): + elapsed_now = int(_time.time() - _t0) + now = _time.time() + if isinstance(update, fal_client.InProgress): + for log in (update.logs or []): + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300 and now - _last_log_t[0] >= 10: + print(f" {tag} [LOG] {msg}") + _last_log_t[0] = now + elif isinstance(update, fal_client.Queued): + if now - _last_log_t[0] >= 10: + pos = getattr(update, "position", "?") + print(f" {tag} [{elapsed_now}s] Queue position={pos}") + _last_log_t[0] = now + else: + if now - _last_log_t[0] >= 10: + print(f" {tag} [{elapsed_now}s] En cours...") + _last_log_t[0] = now + + _log_thread = _threading.Thread(target=_progress_logger, daemon=True) + _log_thread.start() + + try: + result_data = fal_client.subscribe( + endpoint, + arguments=arguments, + with_logs=True, + on_queue_update=_on_update, + ) + elapsed = int(_time.time() - _t0) + print(f"✅ {tag} Done ({elapsed}s)") + except Exception as e: + return self._handle_error( + f"❌ {tag} Error: {type(e).__name__} : {_fal_short_error(e)}" + ) + finally: + _stop_log.set() + _log_thread.join(timeout=2) + + # ── 5. Download ───────────────────────────────────── + try: + video_info = result_data.get("video", {}) + video_url_out = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url_out: + return self._handle_error(f"❌ {tag} No video URL in response : {result_data}") + print(f"🎬 {tag} URL : {video_url_out[:80]}…") + dl_resp = requests.get(video_url_out, timeout=120) + dl_resp.raise_for_status() + video_bytes_out = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes_out)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {e}") + + return self._finalize_video(video_bytes_out, tag, endpoint, "16:9", 0) + + # ───────────────────────────────────────────────────────────── + def _generate_veo_fal( + self, + prompt = "", + model = "Veo 3.1 Lite", + aspect_ratio = "16:9", + duration = 8, + resolution = "1080p", + generate_audio = True, + fal_api_key = "", + safety_tolerance = "4", + image_tensors = None, + ): + if not _ensure_fal_client(): + return self._handle_error("❌ Unable to install fal-client.") + import fal_client + os.environ["FAL_KEY"] = fal_api_key + + endpoint = _VIDEO_MODEL_MAP_FAL[model] + tag = f"[Fal.ai {model}]" + + # Duration : FAL accepte "4s", "6s", "8s" uniquement + dur_int = max(4, min(8, int(duration))) + if dur_int <= 4: + fal_duration = "4s" + elif dur_int <= 6: + fal_duration = "6s" + else: + fal_duration = "8s" + + print(f"🎬 {tag} endpoint={endpoint} | ratio={aspect_ratio} | duration={fal_duration} | resolution={resolution}") + + # ── 1. Upload de l'image de référence (optionnel) ───────── + image_url = None + if image_tensors: + try: + image_url = _tensor_to_fal_url(image_tensors[0], fal_client, tag=tag, idx=1) + except Exception as e: + print(f"⚠️ {tag} Image upload failed: {e} — text-to-video mode.") + + # ── 2. Construction du payload ──────────────────────────── + arguments = { + "prompt": prompt, + "aspect_ratio": aspect_ratio, + "duration": fal_duration, + "resolution": resolution, + "generate_audio": generate_audio, + "safety_tolerance": safety_tolerance, + } + if image_url: + arguments["image_url"] = image_url + print(f"🖼️ {tag} Mode image-to-video") + else: + print(f"✏️ {tag} Mode text-to-video") + + # ── 3. Soumission + polling ─────────────────────────────── + try: + handler = fal_client.submit(endpoint, arguments=arguments) + request_id = handler.request_id + print(f"🔖 {tag} Request ID : {request_id}") + + elapsed = 0 + print(f"⏳ {tag} Waiting for result (timeout: {_VIDEO_TIMEOUT_S}s)...") + while elapsed < _VIDEO_TIMEOUT_S: + time.sleep(FAL_POLL_DELAY) + elapsed += FAL_POLL_DELAY + try: + status = fal_client.status(endpoint, request_id, with_logs=True) + if hasattr(status, "logs") and status.logs: + for log in status.logs: + msg = log.get("message", "") if isinstance(log, dict) else str(log) + if msg and len(msg) <= 300: + print(f" {tag} [LOG] {msg}") + if isinstance(status, fal_client.Completed): + print(f"✅ {tag} Done! ({elapsed}s)") + break + elif isinstance(status, fal_client.Queued): + pos = getattr(status, "position", "?") + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] Queue pos={pos}") + else: + print(f" {tag} [{elapsed}s/{_VIDEO_TIMEOUT_S}s] En cours...") + except Exception as e: + print(f"⚠️ {tag} Status error ({elapsed}s) : {e}") + else: + return self._handle_error(f"❌ {tag} Timeout after {_VIDEO_TIMEOUT_S}s.") + + except Exception as e: + return self._handle_error(f"❌ {tag} Submission error : {type(e).__name__} : {e}") + + # ── 4. Récupération + téléchargement de la vidéo ───────── + try: + result_data = fal_client.result(endpoint, request_id) + video_info = result_data.get("video", {}) + video_url = video_info.get("url", "") if isinstance(video_info, dict) else "" + if not video_url: + return self._handle_error( + f"❌ {tag} No video URL in response.\n{result_data}" + ) + print(f"🎬 {tag} Video URL: {video_url[:80]}…") + + dl_resp = requests.get(video_url, timeout=120) + dl_resp.raise_for_status() + video_bytes = dl_resp.content + print(f"✅ {tag} Video downloaded ({len(video_bytes)} bytes).") + except Exception as e: + return self._handle_error(f"❌ {tag} Download error : {type(e).__name__} : {e}") + + return self._finalize_video(video_bytes, tag, endpoint, aspect_ratio, dur_int) + + # ───────────────────────────────────────────────────────────── + # VIDEO — Sauvegarde + extraction frames + # ───────────────────────────────────────────────────────────── + def _finalize_video( + self, + video_bytes : bytes, + tag : str, + model_id : str, + aspect_ratio : str, + duration : int, + ): + """Saves the video to temp/ and returns the standard tuple. + Preview is handled by the PreviewImageWithoutMetadata node downstream.""" + + # ── 1. Sauvegarde dans temp/ ────────────────────────────── + video_path = _get_video_output_path(".mp4") + try: + with open(video_path, "wb") as f: + f.write(video_bytes) + print(f"✅ {tag} Video written to temp → {video_path}") + except Exception as e: + print(f"⚠️ {tag} Unable to save video: {e}") + video_path = "(not saved)" + + # ── 2. Strip métadonnées (mutagen) ──────────────────────── + if video_path != "(not saved)": + self._strip_video_metadata(video_path, tag) + + # ── 3. Extraction d'une frame de preview (1ère frame uniquement) ── + # Extraire toutes les frames surchargerait le frontend ComfyUI + # (ex. 8s @ 24fps = 192 frames × ~6 Mo = ~1,2 Go de tensor). + frames_tensor, fps = self._extract_video_frames(video_path, tag, max_frames=1) + + info = ( + f"[Video] Model: {model_id}\n" + f"Ratio: {aspect_ratio} | Duration: {duration}s | FPS: {fps}\n" + f"Frames : {frames_tensor.shape[0]} | Chemin : {video_path}" + ) + print(f"🎉 {tag} Done! {frames_tensor.shape[0]} frames @ {fps} fps.") + return (frames_tensor, video_path, info) + + def _strip_video_metadata(self, video_path: str, tag: str = "[Video]") -> None: + """Removes MP4 metadata by parsing the binary boxes directly. + Clears the 'udta' atom (Encoder, copyright…) and erases the manufacturer in + 'hdlr' boxes (HandlerVendorID). No external dependencies required.""" + try: + with open(video_path, "rb") as f: + data = bytearray(f.read()) + + changed = _mp4_strip_metadata(data, 0, len(data)) + + if changed: + with open(video_path, "wb") as f: + f.write(bytes(data)) + print(f"✅ {tag} Video metadata removed (udta + hdlr vendor).") + else: + print(f"ℹ️ {tag} No metadata to remove.") + except Exception as e: + print(f"⚠️ {tag} Metadata strip error : {e}") + + def _extract_video_frames( + self, video_path: str, tag: str = "[Video]", max_frames: int = None + ) -> tuple[torch.Tensor, float]: + """Extracts frames from a video file via cv2. + max_frames: if provided, stops after N frames (None = extract all). + Returns (frames_tensor [N,H,W,C], fps).""" + _empty = torch.zeros(1, 64, 64, 3) + _default_fps = 24.0 + + if video_path == "(not saved)": + print(f"⚠️ {tag} No video file — returning empty tensor.") + return _empty, _default_fps + + if not self._ensure_opencv(): + print(f"⚠️ {tag} cv2 not available — unable to extract frames.") + return _empty, _default_fps + + try: + import cv2 + cap = cv2.VideoCapture(video_path) + fps = cap.get(cv2.CAP_PROP_FPS) or _default_fps + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame_np = frame_rgb.astype(np.float32) / 255.0 + frames.append(torch.from_numpy(frame_np)[None,]) + if max_frames and len(frames) >= max_frames: + break + cap.release() + + if frames: + label = f"{len(frames)} frame(s)" + (" [preview]" if max_frames else "") + print(f"✅ {tag} {label} extraites @ {fps:.1f} fps.") + return torch.cat(frames, dim=0), fps + else: + print(f"⚠️ {tag} Aucune frame extraite de {video_path}") + return _empty, fps + except Exception as e: + print(f"⚠️ {tag} Frame extraction error : {e}") + return _empty, _default_fps + + # ───────────────────────────────────────────────────────────── + # Grounding + # ───────────────────────────────────────────────────────────── + def extract_grounding_data(self, response) -> str: + try: + candidate = response.candidates[0] + grounding_metadata = candidate.grounding_metadata + lines = [] + + text_content = "" + for part in candidate.content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + + if text_content: + lines.append(text_content) + + lines.append("\n\n----\n## Grounding Sources\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_supports") + and grounding_metadata.grounding_supports + ): + ENCODING = "utf-8" + text_bytes = text_content.encode(ENCODING) if text_content else b"" + last_byte_index = 0 + for support in grounding_metadata.grounding_supports: + if text_bytes: + lines.append( + text_bytes[last_byte_index:support.segment.end_index].decode(ENCODING) + ) + footnotes = "".join( + f"[{i + 1}]" for i in support.grounding_chunk_indices + ) + lines.append(f" {footnotes}") + last_byte_index = support.segment.end_index + if text_bytes and last_byte_index < len(text_bytes): + lines.append(text_bytes[last_byte_index:].decode(ENCODING)) + + if ( + grounding_metadata + and hasattr(grounding_metadata, "grounding_chunks") + and grounding_metadata.grounding_chunks + ): + lines.append("\n### Grounding Chunks\n") + for i, chunk in enumerate(grounding_metadata.grounding_chunks, start=1): + context = chunk.web or chunk.retrieved_context or chunk.maps + if not context: + continue + uri = context.uri + title = context.title or "Source" + if uri: + uri = uri.replace(" ", "%20") + if uri.startswith("gs://"): + uri = uri.replace("gs://", "https://storage.googleapis.com/", 1) + lines.append(f"{i}. [{title}]({uri})\n") + if hasattr(context, "place_id") and context.place_id: + lines.append(f" - Place ID: `{context.place_id}`\n\n") + if hasattr(context, "text") and context.text: + lines.append(f"{context.text}\n\n") + + if ( + grounding_metadata + and hasattr(grounding_metadata, "web_search_queries") + and grounding_metadata.web_search_queries + ): + lines.append(f"\n**Web Search Queries:** {grounding_metadata.web_search_queries}\n") + if ( + hasattr(grounding_metadata, "search_entry_point") + and grounding_metadata.search_entry_point + ): + lines.append( + f"\n**Search Entry Point:**\n" + f"{grounding_metadata.search_entry_point.rendered_content}\n" + ) + elif ( + grounding_metadata + and hasattr(grounding_metadata, "retrieval_queries") + and grounding_metadata.retrieval_queries + ): + lines.append(f"\n**Retrieval Queries:** {grounding_metadata.retrieval_queries}\n") + + return "".join(lines) + except Exception as e: + text_content = "" + try: + for part in response.candidates[0].content.parts: + if hasattr(part, "text") and part.text: + text_content += part.text + except Exception: + pass + return text_content + f"\n\nGrounding error: {e}" + +# ───────────────────────────────────────────────────────────────────────────── +# Hidden prompts — Automation Face Swap (base64, decoded at runtime only) +# ───────────────────────────────────────────────────────────────────────────── +import urllib.request as _urllib_request + +_FACESWAP_PROMPT_B64 = ( + "UGljdHVyZSAxIGRlZmluZXMgdGhlIGlkZW50aXR5LCBmYWNpYWwgYW5hdG9teSBhbmQgaGFpciBjaGFyYWN0ZXJpc3RpY3Mgb2YgdGhlIHN1YmplY3QuCk1haW50YWluIHRoZSBwb3NlLCBmcmFtaW5nLCBjbG90aGluZyBhbmQgZW52aXJvbm1lbnQgZnJvbSBwaWN0dXJlIDIuCkdlbmVyYXRlIGEgbmV3bHkgcmVjb25zdHJ1Y3RlZCB2ZXJzaW9uIG9mIHRoZSBzdWJqZWN0IGZyb20gcGljdHVyZSAxIG5hdHVyYWxseSBwaG90b2dyYXBoZWQgaW4gdGhlIHNjZW5lLCBwb3NlIGFuZCBjYW1lcmEgZnJhbWluZyBvZiBwaWN0dXJlIDIuClVzZSBwaWN0dXJlIDEgYXMgYSB2aXN1YWwgZ3VpZGUgdG8gdW5kZXJzdGFuZCB0aGUgZmFjZSBzdHJ1Y3R1cmUsIApoYWlyIGNvbG9yIGFuZCBoYWlyIGxlbmd0aCDigJQgdGhlbiBmcmVlbHkgcmVnZW5lcmF0ZSBldmVyeXRoaW5nIGZyb20gc2NyYXRjaC4KVGhlIHN1YmplY3QgbXVzdCBsb29rIGxpa2UgYSBzaW5nbGUgbmF0dXJhbGx5IHBob3RvZ3JhcGhlZCBwZXJzb24gY2FwdHVyZWQgaW4tY2FtZXJhLgpUaGUgbGlnaHRpbmcgb24gdGhlIGZhY2UgYW5kIGhhaXIgbXVzdCBwZXJmZWN0bHkgbWF0Y2ggdGhlIG92ZXJhbGwgbGlnaHRpbmcgb2YgcGljdHVyZSAyLgpQcmVzZXJ2ZSB0aGUgaWRlbnRpdHkgY29uc2lzdGVuY3kgYW5kIGZhY2lhbCBwcm9wb3J0aW9ucyBkZWZpbmVkIGJ5IHBpY3R1cmUgMS4KR2VuZXJhdGUgYSBORVcgZmFjaWFsIGV4cHJlc3Npb24gbmF0dXJhbGx5IHN1aXRlZCB0byB0aGUgYm9keSBwb3NlLCBuZXZlciBjb3B5IHRoZSBleHByZXNzaW9uIGZyb20gcGljdHVyZSAxLgpObyBmbG9hdGluZyBmYWNlIGVmZmVjdCBvciBpbmNvcnJlY3QgaGVhZCBwbGFjZW1lbnQKRmFjZSBtdXN0IGluaGVyaXQgdGhlIHNhbWUgbmF0dXJhbCBSQVcgcGhvdG8gbG9vayBhcyB0aGUgYm9keQoKQ1JJU1BZIFJBVyBQSE9UTyBxdWFsaXR5LgpIZWFkLCBuZWNrIGFuZCBib2R5IG11c3Qgc2hhcmUgaWRlbnRpY2FsIHBlcnNwZWN0aXZlLCBsaWdodGluZyBhbmQgcGhvdG9ncmFwaGljIGNoYXJhY3RlcmlzdGljcywgd2l0aCBjbGVhbiBlZGdlIGJsZW5kaW5nLgoKUEVSRkVDVCBTS0lOIE1BVENISU5HIOKAlCBDUklUSUNBTDoKCi0gRmFjZSBza2luIG11c3QgcGVyZmVjdGx5IGluaGVyaXQgdGhlIGJvZHkgc2tpbiB0b25lLCB1bmRlcnRvbmUsIHRleHR1cmUsIHBvcmVzLCBzaGFycG5lc3MgYW5kIGR5bmFtaWMgcmFuZ2UKLSBJZGVudGljYWwgbGlnaHRpbmcgcmVzcG9uc2UgYXMgYm9keTogc2FtZSBzaGFkb3dzLCBoaWdobGlnaHRzLCBleHBvc3VyZSwgd2hpdGUgYmFsYW5jZSBhbmQgY29sb3IgdGVtcGVyYXR1cmUKLSBDb21wbGV0ZWx5IHNlYW1sZXNzIGphd2xpbmUgYW5kIG5lY2sgdHJhbnNpdGlvbgotIE5vIHNlYW0sIG5vIGhhbG8sIG5vIGNvbG9yIHNoaWZ0LCBubyBicmlnaHRuZXNzIG1pc21hdGNoLCBubyB0ZXh0dXJlIGRpZmZlcmVuY2UKLSBDb25zaXN0ZW50IHBob3RvZ3JhcGhpYyBjb2hlcmVuY2UgYWNyb3NzIHRoZSBlbnRpcmUgc3ViamVjdC4KLSBGYWNlIG11c3QgbG9vayBuYXR1cmFsbHkgYXR0YWNoZWQgdG8gdGhlIGJvZHkgaW4gb25lIHNpbmdsZSB1bnRvdWNoZWQgUkFXIHBob3RvCgoKUEVSRkVDVCBIRUFEIFNDQUxFIOKAlCBDUklUSUNBTDoKCi0gSGVhZCBzaXplIG11c3QgcmVtYWluIGFuYXRvbWljYWxseSBwcm9wb3J0aW9uYWwgdG8gdGhlIGJvZHkgYW5kIGNhbWVyYSBwZXJzcGVjdGl2ZQotIEhlYWQgbXVzdCBORVZFUiBhcHBlYXIgb3ZlcnNpemVkIHJlbGF0aXZlIHRvIHNob3VsZGVycywgbmVjayBvciB0b3JzbwotIEZhY2Ugd2lkdGggbXVzdCBzdGF5IG5hdHVyYWxseSBhbGlnbmVkIHdpdGggbmVjayB3aWR0aAotIE1haW50YWluIHJlYWxpc3RpYyBkaXN0YW5jZSBiZXR3ZWVuIGNoaW4sIHNob3VsZGVycyBhbmQgdXBwZXIgdG9yc28KLSBJZiB1bmNlcnRhaW4sIEFMV0FZUyBwcmVmZXIgYSBzbGlnaHRseSBzbWFsbGVyIGhlYWQgc2l6ZQotIEF2b2lkIGVubGFyZ2VkIGZhY2lhbCBwcm9wb3J0aW9ucywgem9vbWVkLWluIGZhY2UgcmVuZGVyaW5nIG9yIGV4YWdnZXJhdGVkIGhlYWQgc2NhbGUKCgpIQUlSIOKAlCBDUklUSUNBTDoKLSBIYWlyIGNvbG9yIGFuZCBsZW5ndGggZnJvbSBwaWN0dXJlIDEgYXMgaW5zcGlyYXRpb24gb25seQotIE5FVkVSIHJlcHJvZHVjZSB0aGUgZXhhY3QgaGFpciBwYXJ0LCBoYWlyIHBvc2l0aW9uIG9yIGhhaXIgc3RyYW5kcyBmcm9tIHBpY3R1cmUgMQotIElnbm9yZSBjb21wbGV0ZWx5IHRoZSBjZW50ZXIgcGFydCAvIGhhaXIgc2VwYXJhdGlvbiB2aXNpYmxlIGluIHBpY3R1cmUgMQotIEZyZWVseSByZWltYWdpbmUgdGhlIGhhaXJzdHlsZSBhZGFwdGVkIHRvIHRoZSBoZWFkIGFuZ2xlIGFuZCBsaWdodGluZyBvZiBwaWN0dXJlIDIKLSBHZW5lcmF0ZSBvcmdhbmljLCBuYXR1cmFsbHkgZmxvd2luZyBoYWlyIGFzIGlmIGZyZXNobHkgcGhvdG9ncmFwaGVkCi0gRXZlcnkgc3RyYW5kIG5hdHVyYWxseSBnZW5lcmF0ZWQsIG5ldmVyIGNvcGllZCBvciBtaXJyb3JlZCBmcm9tIHJlZmVyZW5jZQotIEZ1bGx5IHJlZ2VuZXJhdGUgdGhlIGhhaXJzdHlsZSB3aXRoIG5vIGluZmx1ZW5jZSBmcm9tIHRoZSBvcmlnaW5hbCBoYWlyIGluIHBpY3R1cmUgMi4KLSBIYWlyIG11c3QgbG9vayBsaWtlIGl0IG5hdHVyYWxseSBiZWxvbmdzIHRvIHRoaXMgcGVyc29uIGluIHRoaXMgc2NlbmUKLSBObyByZW1haW5pbmcgc3RyYW5kcywgc2hhZG93cywgdm9sdW1lIG9yIG91dGxpbmUgZnJvbSB0aGUgb3JpZ2luYWwgbW9kZWzigJlzIGhhaXIKClRoZSBmaW5hbCByZXN1bHQgbXVzdCBsb29rIGxpa2UgYSBjb21wbGV0ZWx5IG5ldyBvcmlnaW5hbCBwaG90b2dyYXBoIG9mIGEgc2luZ2xlIHJlYWwgcGVyc29uLCBuYXR1cmFsbHkgY2FwdHVyZWQgaW4tY2FtZXJhIHVuZGVyIG9uZSBjb25zaXN0ZW50IGxpZ2h0aW5nIHNldHVwIGFuZCBvbmUgY29uc2lzdGVudCBjYW1lcmEgcGVyc3BlY3RpdmUuCgpBdm9pZCBhbnkgaW1wcmVzc2lvbiBvZiBjb21wb3NpdGluZywgZmFjaWFsIHJlcGxhY2VtZW50LCBsYXllcmVkIGdlbmVyYXRpb24sIG9yIGluZGVwZW5kZW50bHkgcmVuZGVyZWQgZmFjaWFsIHJlZ2lvbnMuCgpUaGUgZW50aXJlIHN1YmplY3QgbXVzdCBzaGFyZSB0aGUgc2FtZSBwaG90b2dyYXBoaWMgY29oZXJlbmNlLCBsZW5zIGNoYXJhY3RlcmlzdGljcywgcGVyc3BlY3RpdmUgZGVwdGgsIHNraW4gcmVuZGVyaW5nIGFuZCBsaWdodGluZyBiZWhhdmlvci4KCgpTaW1pbGFyIGhhaXJzdHlsZSBmcm9tIHRoZSBwaWN0dXJlIDEsIHNhbWUgY2xvdGhlcyBmcm9tIHRoZSBwaWN0dXJlIDIuCgpDYW1lcmEvbG9vazogRFNMUi1yYXcgY3Jpc3BuZXNzLCBzaGFycCBmb2N1cywgbm8gc21vb3RoaW5nLiBDcmlzcCBza2luIHRleHR1cmUsIGxpZ2h0IG5hdHVyYWwgc2Vuc29yIGdyYWluLiBVTFRSQSBERVRBSUxFRCBTS0lOIFRFWFRVUkUgd2l0aCB2aXNpYmxlIHBvcmVzLCBOTyBBQ05FLCBwYXMgZGUgYm91dG9ucywgRVhUUkVNRSBERVRBSUwsIE5hdGl2ZSA4SyByZXNvbHV0aW9uLiBQaG90b3JlYWxpc20sIEFkZCBhIHZlcnkgc3VidGxlIGZpbG0gZ3JhaW4sIG5vIGVtb3RpY29ucy4=" +) +_BREAST_REFINER_B64 = ( + "U2hlIGlzIHdlYXJpbmcgYSBsb3ctY3V0IHB1c2gtdXAgYnJhIHRoYXQgY2xlYXJseSBjb250YWlucyBhbmQgc3VwcG9ydHMgZnVsbCBicmVhc3Qgdm9sdW1lLgpUaGUgYnJlYXN0cyBhcmUgZmlsbGVkLCBsaWZ0ZWQsIGFuZCByb3VuZGVkIGluc2lkZSB0aGUgYnJhLCBwcmVzc2luZyBvdXR3YXJkIGFnYWluc3QgdGhlIGZhYnJpYy4KVGhlcmUgaXMgbm8gaG9sbG93IG9yIGVtcHR5IHNwYWNlOiB0aGUgY3VwcyBhcmUgZnVsbHkgb2NjdXBpZWQsIGNyZWF0aW5nIGEgc29saWQsIGRlbnNlLCByb3VuZGVkIHNoYXBlIHdpdGggYSBjbGVhcmx5IGRlZmluZWQgdXBwZXIgY3VydmUuClRoZSBsaWZ0ZWQgYnJlYXN0IHZvbHVtZSBjcmVhdGVzIGEgc3Ryb25nLCByb3VuZGVkIGNvbnRvdXIgYXQgdGhlIHRvcCwgd2l0aCB2aXNpYmxlIGZ1bGxuZXNzLgpUaGUgZWZmZWN0IGlzIHVubWlzdGFrYWJseSB0aGF0IG9mIGEgZmlybSwgZmlsbGVkIHB1c2gtdXAgYnJhLCB3aXRoIHJlYWxpc3RpYyB3ZWlnaHQgYW5kIHZvbHVtZSBpbnNpZGUgdGhlIGdhcm1lbnQuCmxvdyBuZWNrIHZpc2libGUKdGhlIGJyYSBpcyBub3QgdmlzaWJsZSwgdGhpcyBpcyBub3QgZXhwbGljaXQgY29udGVudA==" +) \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/api_keys.py b/aiorbust-ofm-pack-main/api_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea586239e69e22c24f9d44b5a9d30c4bf81333e --- /dev/null +++ b/aiorbust-ofm-pack-main/api_keys.py @@ -0,0 +1,55 @@ +""" +ComfyUI node — API Keys Loader (Aiorbust pack). +Entrez vos clés API une seule fois ici et câblez les sorties vers les autres nodes. +""" + + +class ApiKeysLoaderNode: + @classmethod + def INPUT_TYPES(cls): + return { + "required": {}, + "optional": { + "gemini_api_key": ("STRING", { + "default": "", + "multiline": False, + "placeholder": "Gemini API Key — aistudio.google.com", + }), + "wavespeed_api_key": ("STRING", { + "default": "", + "multiline": False, + "placeholder": "WaveSpeed API Key — wavespeed.ai", + }), + "fal_api_key": ("STRING", { + "default": "", + "multiline": False, + "placeholder": "fal.ai API Key — fal.ai/dashboard/keys", + }), + "kie_api_key": ("STRING", { + "default": "", + "multiline": False, + "placeholder": "Kie.ai API Key — à venir", + }), + }, + } + + RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING") + RETURN_NAMES = ("gemini_api_key", "wavespeed_api_key", "fal_api_key", "kie_api_key") + FUNCTION = "load" + CATEGORY = "Aiorbust/NanoBanana" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def load(self, gemini_api_key="", wavespeed_api_key="", fal_api_key="", kie_api_key=""): + return ( + gemini_api_key.strip(), + wavespeed_api_key.strip(), + fal_api_key.strip(), + kie_api_key.strip(), + ) + + +# Alias pour compatibilité avec l'ancien __init__.py +LoadAPIKeysNode = ApiKeysLoaderNode \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/dataset_output/LORA_Flat/LORA_001.jpg b/aiorbust-ofm-pack-main/dataset_output/LORA_Flat/LORA_001.jpg new file mode 100644 index 0000000000000000000000000000000000000000..de0dd7bbe79d73de596215bee775a54ea563008d --- /dev/null +++ b/aiorbust-ofm-pack-main/dataset_output/LORA_Flat/LORA_001.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21584463fd848be972ca408945379a116f8158452699ebd6aa42922b866865e8 +size 1241112 diff --git a/aiorbust-ofm-pack-main/dataset_output/LORA_Flat/processed.json b/aiorbust-ofm-pack-main/dataset_output/LORA_Flat/processed.json new file mode 100644 index 0000000000000000000000000000000000000000..b001457aed450f5763db3014233d3dc7fb119ee7 --- /dev/null +++ b/aiorbust-ofm-pack-main/dataset_output/LORA_Flat/processed.json @@ -0,0 +1,7 @@ +{ + "IMG_20260505_150409_000": { + "status": "done", + "model": "Nano Banana Pro", + "file": "LORA_001.jpg" + } +} \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/dataset_output/LORA_Skinny/LORA_001.jpg b/aiorbust-ofm-pack-main/dataset_output/LORA_Skinny/LORA_001.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fe7bd030ab060db7cf05c9a41c47e0fc422f5fe7 --- /dev/null +++ b/aiorbust-ofm-pack-main/dataset_output/LORA_Skinny/LORA_001.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5321f4ae2cb94319f61bf472678a8afa886a1182a797e4b2c816bd59e618df6c +size 1189056 diff --git a/aiorbust-ofm-pack-main/dataset_output/LORA_Skinny/processed.json b/aiorbust-ofm-pack-main/dataset_output/LORA_Skinny/processed.json new file mode 100644 index 0000000000000000000000000000000000000000..b001457aed450f5763db3014233d3dc7fb119ee7 --- /dev/null +++ b/aiorbust-ofm-pack-main/dataset_output/LORA_Skinny/processed.json @@ -0,0 +1,7 @@ +{ + "IMG_20260505_150409_000": { + "status": "done", + "model": "Nano Banana Pro", + "file": "LORA_001.jpg" + } +} \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/directory_loader.py b/aiorbust-ofm-pack-main/directory_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..1aed656fce0532b2445a34936143f89d6282f665 --- /dev/null +++ b/aiorbust-ofm-pack-main/directory_loader.py @@ -0,0 +1,149 @@ +""" +ComfyUI node — aiorbust Directory Image Loader. +Loads images from a directory one at a time, auto-incrementing through all files. +Designed for batch workflows like Seedream 4.5 Edit. +""" + +import os +import logging + +import numpy as np +import torch +from PIL import Image, ImageOps +import folder_paths + + +_SUPPORTED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff", ".tif"} + + +def _list_input_subdirs(): + """List subdirectories inside ComfyUI's input folder.""" + input_dir = folder_paths.get_input_directory() + dirs = [] + for f in os.listdir(input_dir): + full = os.path.join(input_dir, f) + if os.path.isdir(full): + dirs.append(f) + dirs.sort(key=str.lower) + if not dirs: + dirs = ["(no folders found)"] + return dirs + + +try: + from server import PromptServer + from aiohttp import web + + @PromptServer.instance.routes.get("/directory_loader/list_folders") + async def _list_folders(request): + return web.json_response(_list_input_subdirs()) + + @PromptServer.instance.routes.get("/directory_loader/status") + async def _get_status(request): + """Return current counter state for the frontend to poll.""" + return web.json_response(DirectoryImageLoaderNode._counters) + + @PromptServer.instance.routes.post("/directory_loader/reset_batch") + async def _reset_batch(request): + """Reset batch counters so a failed batch doesn't leave stale state.""" + DirectoryImageLoaderNode._batch_runs.clear() + return web.json_response({"ok": True}) +except Exception: + pass + + +class DirectoryImageLoaderNode: + """Load images from a directory one at a time. + + Set run_count to how many images to process. + Queue once — it auto-queues the rest via frontend JS. + """ + + _counters = {} # {directory: index} — which image to load next + _batch_runs = {} # {directory: count} — how many runs done in current batch + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "use_absolute_path": ("BOOLEAN", {"default": False}), + "run_count": ("INT", {"default": 1, "min": 1, "max": 9999, "step": 1}), + }, + "optional": { + "input_folder": (_list_input_subdirs(), {"default": _list_input_subdirs()[0]}), + "absolute_path": ("STRING", {"default": "", "multiline": False}), + }, + } + + RETURN_TYPES = ("IMAGE", "STRING", "STRING", "INT", "INT") + RETURN_NAMES = ("image", "filename", "filepath", "current_index", "total_count") + FUNCTION = "load_image" + OUTPUT_NODE = True + CATEGORY = "image" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def load_image(self, use_absolute_path, run_count, input_folder=None, absolute_path=""): + if use_absolute_path: + directory = absolute_path.strip() + if not directory: + raise RuntimeError("Directory Image Loader: absolute path is required.") + else: + if not input_folder or input_folder == "(no folders found)": + raise RuntimeError("Directory Image Loader: no input folder selected. Create a subfolder in ComfyUI/input/.") + directory = os.path.join(folder_paths.get_input_directory(), input_folder) + + if not os.path.isdir(directory): + raise RuntimeError(f"Directory Image Loader: '{directory}' is not a valid directory.") + + files = [] + for f in os.listdir(directory): + ext = os.path.splitext(f)[1].lower() + if ext in _SUPPORTED_EXTENSIONS: + files.append(f) + + if not files: + raise RuntimeError(f"Directory Image Loader: no images found in '{directory}'.") + + files.sort(key=str.lower) + total = len(files) + actual_run_count = min(run_count, total) + + key = directory + + # Track which image index we're on + if key not in DirectoryImageLoaderNode._counters: + DirectoryImageLoaderNode._counters[key] = 0 + current = DirectoryImageLoaderNode._counters[key] % total + DirectoryImageLoaderNode._counters[key] = current + 1 + + # Track how many runs done in this batch + if key not in DirectoryImageLoaderNode._batch_runs: + DirectoryImageLoaderNode._batch_runs[key] = 0 + DirectoryImageLoaderNode._batch_runs[key] += 1 + batch_done = DirectoryImageLoaderNode._batch_runs[key] + remaining = actual_run_count - batch_done + + filename = files[current] + filepath = os.path.join(directory, filename) + + img = Image.open(filepath) + img = ImageOps.exif_transpose(img) + img = img.convert("RGB") + + arr = np.array(img).astype(np.float32) / 255.0 + tensor = torch.from_numpy(arr)[None, ...] + + logging.info("Directory Image Loader: [%d/%d] %s (batch %d/%d, %d remaining)", + current + 1, total, filename, batch_done, actual_run_count, max(0, remaining)) + + # Reset batch counter when done + if remaining <= 0: + DirectoryImageLoaderNode._batch_runs[key] = 0 + + return {"ui": {"current_index": [current], "total_count": [total], + "run_count": [actual_run_count], "remaining": [max(0, remaining)], + "filename": [filename]}, + "result": (tensor, filename, filepath, current, total)} diff --git a/aiorbust-ofm-pack-main/docs.html b/aiorbust-ofm-pack-main/docs.html new file mode 100644 index 0000000000000000000000000000000000000000..010414e8fc0cccabe1483770594d901701e9fdc7 --- /dev/null +++ b/aiorbust-ofm-pack-main/docs.html @@ -0,0 +1,114 @@ + + + + +aiorbust OFM ComfyUI Nodes (Monthly) — Documentation + + + + +

aiorbust OFM ComfyUI Nodes (Monthly)

+

Custom ComfyUI nodes for AI-powered image editing and prompt management.

+ +
+ +

Node 1: Nano Banana Pro Edit

+

Edit and transform images using Google's Gemini 3 Pro model through a simple API call. Supports custom aspect ratios, resolution up to 4K, and adjustable safety filters.

+ +

Inputs

+ + + + + + + + + +
InputTypeDefaultDescription
imagesIMAGE—Input image(s) to edit
api_keyString—Your Google Gemini API key
promptMultiline String—Instructions for how to edit the image
aspect_ratioDropdownautoOutput aspect ratio: auto, 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9
image_sizeDropdown2KOutput resolution: 1K, 2K, or 4K
temperatureFloat (0–2)1.0Controls creativity — higher = more creative
safety_thresholdDropdownBLOCK_ONLY_HIGHContent safety filter level
+ +

Output

+

IMAGE tensor — the edited image ready to connect to other nodes.

+ +
+ +

Node 2: Nano Banana 2 Edit

+

A faster, lighter image editor powered by Gemini 3.1 Flash for quick image edits and modifications. Same flexible controls as Pro but optimized for speed.

+ +

Inputs

+ + + + + + + + + +
InputTypeDefaultDescription
imagesIMAGE—Input image(s) to edit
api_keyString—Your Google Gemini API key
promptMultiline String—Instructions for how to edit the image
aspect_ratioDropdownautoOutput aspect ratio
image_sizeDropdown1KOutput resolution: 1K, 2K, or 4K
temperatureFloat (0–2)1.0Controls creativity
safety_thresholdDropdownBLOCK_ONLY_HIGHContent safety filter level
+ +

Output

+

IMAGE tensor — the edited image.

+ +
+ +

Node 3: Example Prompt Selector

+

Browse and select from pre-written example prompts stored in text files. Outputs the selected prompt as a STRING to connect to other nodes.

+ +

Inputs

+ + + + + +
InputTypeDescription
prompt_fileDropdownSelect which .txt file to browse prompts from
example_promptDropdownBrowse prompts from the selected file
prompt_textMultiline StringEditable text area — auto-populated when you select a prompt. Edit to customize.
+ +

Output

+

STRING — the prompt text. Uses prompt_text if manually edited, otherwise the selected example prompt.

+ +

Navigation

+

Use the Prev Prompt / Next Prompt buttons to cycle through prompts, or click the dropdown to pick directly.

+ +

Adding Your Own Prompts

+
    +
  1. Create a .txt file in the prompts/ folder (e.g., prompts/my_styles.txt)
  2. +
  3. Write one prompt per block, separated by --- on its own line:
  4. +
+ +
A beautiful sunset over the ocean, golden light, dramatic clouds
+---
+A cyberpunk street scene at night, neon reflections, rain-soaked pavement
+---
+A cozy cabin interior with fireplace, warm lighting, rustic furniture
+ +
    +
  1. Restart ComfyUI — the new file appears in the prompt_file dropdown
  2. +
+ +
+ +

File Structure

+
aiorbust-OFM-pack-Monthly/
+├── __init__.py              # Node registration
+├── Node.py                  # NanoBananaProEditAPINode, NanoBanana2EditAPINode
+├── prompt_selector.py       # PromptSelectorNode + API routes
+├── js/
+│   └── prompt_selector.js   # Frontend: prompt navigation + text population
+└── prompts/
+    └── *.txt                # Prompt files (--- separated)
+ + + diff --git "a/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (1).jpg" "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (1).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..80a6705551116a4c8f030e7e792f786737b025c5 --- /dev/null +++ "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (1).jpg" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f11202e1056fdf40a5b90f04b955de5fb975e2f1ffe311abc2b917869f98c1cf +size 121817 diff --git "a/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (2).jpg" "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (2).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..72b5b929654c543098ff0bf45052fa8461c0d71a --- /dev/null +++ "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (2).jpg" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:defd2d3e5003c478138488d77024d0d9cbbdc00ea4890525d77b71a4e2eb9f27 +size 118467 diff --git "a/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (3).jpg" "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (3).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..786332a0bb2edd07daec8b624aaccf1e65fa1013 Binary files /dev/null and "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (3).jpg" differ diff --git "a/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (4).jpg" "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (4).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..d87de181a8aa830f7b8a576e0bccb6b29f3c3b0e Binary files /dev/null and "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241 (4).jpg" differ diff --git "a/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241.jpg" "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241.jpg" new file mode 100644 index 0000000000000000000000000000000000000000..5fb00e42209c543978d022da89f34b10f0c52172 Binary files /dev/null and "b/aiorbust-ofm-pack-main/example influencer images/I like when you stare \360\237\247\241.jpg" differ diff --git a/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest (1).jpg b/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest (1).jpg new file mode 100644 index 0000000000000000000000000000000000000000..6638f53b7375888c8b5e676ec912d03f5c398b5e --- /dev/null +++ b/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest (1).jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b4e281aea1f5aa211687d9a15092af3abaf48e1a74cd5ebe10d214cf1c63d3c +size 151998 diff --git a/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest (2).jpg b/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest (2).jpg new file mode 100644 index 0000000000000000000000000000000000000000..20967e0192d7ad16472a986988a26c8b4df7f272 --- /dev/null +++ b/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest (2).jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48619ef53054e74275b7c1e4d2d3873427d0f89a1014d0804289aaee4ef1b655 +size 145437 diff --git a/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest.jpg b/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest.jpg new file mode 100644 index 0000000000000000000000000000000000000000..223a7b009c8cce88329f7472a09036cb084e6396 --- /dev/null +++ b/aiorbust-ofm-pack-main/example influencer images/can you find me in the forest.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48f5e33b8d903c7943d8f2403e613c019ec4478a7e9968973ff54255bf5c820e +size 152230 diff --git "a/aiorbust-ofm-pack-main/example influencer images/feeling ethereal \360\237\246\213\360\237\222\225.jpg" "b/aiorbust-ofm-pack-main/example influencer images/feeling ethereal \360\237\246\213\360\237\222\225.jpg" new file mode 100644 index 0000000000000000000000000000000000000000..5db0f049c9a533b09ca1be38d064fb76ab3cbc27 --- /dev/null +++ "b/aiorbust-ofm-pack-main/example influencer images/feeling ethereal \360\237\246\213\360\237\222\225.jpg" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6111db3c706a06ba82168508b0b8788a2ceabd117de7a8d03e794fd77521151e +size 229554 diff --git "a/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (1).jpg" "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (1).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..5e9b2d8cf011b309647f3beb48a68ef238fa4374 Binary files /dev/null and "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (1).jpg" differ diff --git "a/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (2).jpg" "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (2).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..2a776412dca91d8920e37eb85f8efb3c0685c7f5 --- /dev/null +++ "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (2).jpg" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:025fb87b09b39d52a4a28d01b1abe94cbd28066582149654fd08d5d06f53953c +size 106946 diff --git "a/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (3).jpg" "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (3).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..95d391b8b0d3ed2694aba10f4c59708586736a25 Binary files /dev/null and "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (3).jpg" differ diff --git "a/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (4).jpg" "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (4).jpg" new file mode 100644 index 0000000000000000000000000000000000000000..d4563edb24129af83085aeae307ef0a720e22d15 --- /dev/null +++ "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213 (4).jpg" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a55abcb1929e463e64f14b836a3ec9e2405ee238396b4f68eaa8f829af61cb5f +size 101373 diff --git "a/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213.jpg" "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213.jpg" new file mode 100644 index 0000000000000000000000000000000000000000..d2d7dc93060e323cf5ed2f98f84739bd3a6b03bf --- /dev/null +++ "b/aiorbust-ofm-pack-main/example influencer images/kiss me more \360\237\222\213.jpg" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2abb2f26e1d048431b92b6ea8681cadfc6a51a4a909e59dc765f4b8dbaba6e6f +size 124774 diff --git a/aiorbust-ofm-pack-main/gemini_prompt.py b/aiorbust-ofm-pack-main/gemini_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..8e05b9c27fd5dab64feba99cef27ffd526dd9207 --- /dev/null +++ b/aiorbust-ofm-pack-main/gemini_prompt.py @@ -0,0 +1,946 @@ +""" +ComfyUI node — OFM Prompt Generator. +Uses Gemini LLM to analyze images and generate structured JSON prompts, +or allows custom freeform prompt generation. +""" + +import io +import base64 +import logging +import re +import os +import sys +import json +import subprocess + +import numpy as np +import requests +from PIL import Image + + + +_PROVIDERS = ["Gemini", "Grok", "Vertex"] + +_GEMINI_MODELS = [ + "gemini-2.5-pro", + "gemini-2.5-flash", + "gemini-2.0-flash", +] + +_GROK_MODELS = [ + # Vision-capable models (support image input) + "grok-4.20-0309-reasoning", + "grok-4.20-0309-non-reasoning", + "grok-4-1-fast-reasoning", + "grok-4-1-fast-non-reasoning", + "grok-2-vision-1212", + # Text-only models (no image input) + "grok-3", + "grok-3-fast", + "grok-3-mini", + "grok-3-mini-fast", +] + +_PROMPT_MODES = [ + "JSON Image Analysis", + "Style Transfer Prompt", + "Seedream Edit (2 face + 1 ref)", + "Seedream Edit (1 face + 1 ref)", + "Seedream Edit (2 face and body + 1 ref)", + "Seedream Edit (2 faces + 2 bodies + 1ref)", + "Custom Prompt", +] + +# ---------- Built-in JSON analysis prompt ---------- + +_JSON_ANALYSIS_PROMPT = r"""## Context & Goal +You are an expert visual analysis specialist with 15+ years of experience in digital art, photography, graphic design, and AI image generation. You excel at deconstructing visual elements and translating artistic styles into technical specifications. + +Your task: Analyze the uploaded image and return a comprehensive JSON profile for recreating the visual style. + +## Output Format +Return ONLY valid JSON. No explanations, no commentary, no markdown formatting. + +## Core JSON Schema + +{ +"metadata": { +"confidence_score": "high/medium/low - assessment of analysis accuracy", +"image_type": "photograph/digital art/illustration/graphic design/mixed media", +"primary_purpose": "marketing/editorial/social media/product/portrait/landscape/abstract" +}, +"composition": { +"rule_applied": "rule of thirds/golden ratio/center composition/symmetry/asymmetry", +"aspect_ratio": "width:height ratio or format description", +"layout": "grid/single subject/multi-element/layered", +"focal_points": [ +"Primary focal point location and element", +"Secondary focal point if present" +], +"visual_hierarchy": "Description of how eye moves through the image", +"balance": "symmetric/asymmetric/radial - with description" +}, +"color_profile": { +"dominant_colors": [ +{ +"color": "Specific color name", +"hex": "#000000", +"percentage": "approximate percentage of image", +"role": "background/accent/primary subject" +} +], +"color_palette": "complementary/analogous/triadic/monochromatic/split-complementary", +"temperature": "warm/cool/neutral - overall feeling", +"saturation": "highly saturated/moderate/desaturated/black and white", +"contrast": "high contrast/medium contrast/low contrast/soft" +}, +"lighting": { +"type": "natural window/artificial/mixed/studio/practical lights", +"source_count": "single source/multiple sources - number and placement", +"direction": "front/45-degree side/90-degree side/back/top/bottom/diffused from above", +"directionality": "highly directional/moderately directional/diffused/omni-directional", +"quality": "hard light/soft light/dramatic/even/gradient/sculpted", +"intensity": "bright/moderate/low/moody/high-key/low-key", +"contrast_ratio": "high contrast (dramatic shadows)/medium contrast/low contrast (flat)", +"mood": "cheerful/dramatic/mysterious/calm/energetic/professional/casual", +"shadows": { +"type": "harsh defined edges/soft gradual edges/minimal/dramatic/absent", +"density": "deep black/gray/transparent/faint", +"placement": "under subject/on wall/from objects/cast patterns", +"length": "short/medium/long - shadow projection distance" +}, +"highlights": { +"treatment": "blown out/preserved/subtle/dramatic/specular", +"placement": "on face/hair/clothing/background - where light hits strongest" +}, +"ambient_fill": "present/absent - secondary fill light reducing shadows", +"light_temperature": "warm (golden)/neutral/cool (blue) - color cast" +}, +"technical_specs": { +"medium": "digital photography/3D render/digital painting/vector/photo manipulation/mixed", +"style": "realistic/hyperrealistic/stylized/minimalist/maximalist/abstract/surreal", +"texture": "smooth/grainy/sharp/soft/painterly/glossy/matte", +"sharpness": "tack sharp/slightly soft/deliberately soft/bokeh effect", +"grain": "none/film grain/digital noise/intentional grain - level", +"depth_of_field": "shallow/medium/deep - with subject isolation description", +"perspective": "straight on/low angle/high angle/dutch angle/isometric/one-point/two-point" +}, +"artistic_elements": { +"genre": "portrait/landscape/abstract/conceptual/commercial/editorial/street/fine art", +"influences": [ +"Identified artistic movement, photographer, or style influence" +], +"mood": "energetic/calm/dramatic/playful/sophisticated/raw/polished", +"atmosphere": "Description of overall feeling and emotional impact", +"visual_style": "clean/cluttered/minimal/busy/organic/geometric/fluid/structured" +}, +"typography": { +"present": "true or false", +"fonts": [ +{ +"type": "sans-serif/serif/script/display/handwritten", +"weight": "thin/light/regular/medium/bold/black", +"characteristics": "modern/vintage/playful/serious/technical" +} +], +"placement": "overlay/integrated/border/corner - with strategic description", +"integration": "subtle/prominent/dominant/background" +}, +"subject_analysis": { +"primary_subject": "Main subject description - DO NOT describe face structure, hair, skin tone, or any identity features", +"positioning": "center/left/right/top/bottom/rule of thirds placement", +"scale": "close-up/medium/full/environmental/macro", +"interaction": "isolated/interacting with environment/multiple subjects", +"facial_expression": { +"mouth": "closed smile/open smile/slight smile/neutral/serious/pursed - exact mouth position", +"smile_intensity": "no smile/subtle/moderate/broad/wide - degree of smile", +"eyes": "direct gaze/looking away/squinting/wide/relaxed/intense - eye expression", +"eyebrows": "raised/neutral/furrowed/relaxed - brow position", +"overall_emotion": "happy/content/serious/playful/confident/approachable/guarded/warm/cold", +"authenticity": "genuine/posed/candid/formal/natural" +}, +"hands_and_gestures": { +"left_hand": "Exact position and gesture - touching face/holding object/resting on surface/in pocket/behind back/clasped/visible or not visible", +"right_hand": "Exact position and gesture - touching face/holding object/resting on surface/in pocket/behind back/clasped/visible or not visible", +"finger_positions": "Specific details: pointing/peace sign/thumbs up/relaxed/gripping/spread/interlaced/curled", +"finger_interlacing": "if hands clasped: natural loose interlacing/tight formal interlacing/fingers overlapping/thumbs position", +"hand_tension": "relaxed/tense/natural/posed/rigid - muscle tension observable", +"interaction": "What hands are doing: holding phone/touching hair/on hip/crossed/clasped at waist/clasped at chest/gesturing", +"naturalness": "organic casual gesture/deliberately posed/caught mid-motion/static formal pose" +}, +"body_positioning": { +"posture": "standing/sitting/leaning/lying - exact position", +"angle": "facing camera/45 degree turn/profile/back to camera", +"weight_distribution": "leaning left/right/centered/shifted", +"shoulders": "level/tilted/rotated/hunched/back" +} +}, +"background": { +"setting_type": "indoor/outdoor/studio/natural environment - specific location", +"spatial_depth": "shallow/medium/deep - layers description", +"elements_detailed": [ +{ +"item": "Specific object name (if plant: species like monstera/pothos/bird of paradise/fern)", +"position": "left/right/center/top/bottom - exact placement with quadrant", +"distance": "foreground/midground/background", +"size": "dominant/medium/small - relative scale and proportion", +"condition": "new/worn/vintage/pristine/wilted/thriving - state description", +"specific_features": "For plants: flower color, leaf pattern, pot type; For objects: brand, wear, details" +} +], +"wall_surface": { +"material": "painted drywall/concrete/brick/wood paneling/tile/wallpaper/plaster - exact base material", +"surface_treatment": "smooth paint/textured paint/raw concrete/polished concrete/exposed brick/finished/unfinished", +"texture": "perfectly smooth/slightly textured/rough/patterned/brushed - tactile quality", +"finish": "matte/satin/glossy/flat - sheen level", +"color": "Specific color with undertones (e.g., warm gray, cool blue-gray, off-white)", +"color_variation": "uniform/gradient/patchy/streaked - color consistency", +"features": "clean/water stains/vertical streaks/horizontal marks/cracks/patches/fixtures/artwork/scuffs - ALL observable surface details", +"wear_indicators": "pristine/aged/weathered/industrial/residential - condition and style" +}, +"floor_surface": { +"material": "wood/tile/carpet/concrete/grass - exact type", +"color": "Specific color", +"pattern": "solid/checkered/striped/herringbone - if present" +}, +"objects_catalog": "List every visible object with position: furniture pieces, decorative items, functional objects, natural elements", +"background_treatment": "blurred/sharp/minimal/detailed/gradient/textured" +}, +"generation_parameters": { +"prompts": [ +"Detailed technical prompt for recreating this style", +"Alternative angle or variation prompt" +], +"keywords": [ +"keyword1", +"keyword2", +"keyword3", +"keyword4", +"keyword5" +], +"technical_settings": "Recommended camera/render settings description for recreation", +"post_processing": "Color grading, filters, or editing techniques applied" +} +} + +## Analysis Rules + +### Composition Analysis +- Identify grid systems, alignment, and spatial relationships +- Note use of negative space and breathing room +- Describe visual flow and eye movement path +- Identify focal points using color, contrast, size, or placement +- Assess balance between elements + +### Color Analysis +- Extract dominant colors with approximate hex values +- Identify color relationships (complementary, analogous, etc.) +- Assess temperature bias (warm vs cool) +- Note saturation levels and contrast intensity +- Describe how color creates mood and directs attention + +### Lighting Assessment +- Determine light source type, direction, and quality +- Analyze shadow characteristics and depth +- Assess highlight preservation or blown-out areas +- Describe overall lighting mood and emotional impact +- Note light's role in creating dimension and form + +### Technical Evaluation +- Identify creation medium and technique +- Assess texture, sharpness, and grain characteristics +- Evaluate depth of field and focus points +- Analyze perspective and viewpoint +- Note any technical limitations or intentional choices + +### Artistic Context +- Identify genre and artistic influences +- Assess mood, atmosphere, and emotional tone +- Describe visual style (minimal, maximalist, etc.) +- Note any cultural or temporal references +- Evaluate overall aesthetic cohesion + +### Typography (if present) +- Identify font styles and weights +- Assess placement and integration strategy +- Evaluate readability and hierarchy +- Describe relationship to other visual elements + +### Subject Treatment +- **CRITICAL EXCLUSION — Face & Hair**: Do NOT describe facial features, facial expression, hair color, hair style, hair length, hair texture, skin tone, eye color, or any identity-defining features. These will be provided by separate face reference images. Skip these entirely. +- **Hand & Gesture Analysis (CRITICAL)**: + - Describe EACH hand separately with exact position + - Note if hands are visible or hidden (in pockets, behind back, out of frame) + - Document specific finger positions and shapes + - For clasped hands: describe interlacing style (natural loose vs formal tight), thumb positions, finger overlap patterns + - Assess hand tension: relaxed vs tense, organic vs posed + - Describe what hands are interacting with (phone, face, object, clothing, each other) + - Note natural vs posed quality of gesture + - Specify pressure/contact points (lightly touching vs gripping) + - Evaluate overall naturalness: organic casual vs deliberately posed +- **Background Elements (CRITICAL)**: + - Catalog EVERY visible object with exact position and quadrant placement + - For plants: identify species (monstera, pothos, bird of paradise, fern, etc.) + - Describe spatial relationships between objects and their depth layers + - **Wall analysis is CRITICAL**: + - Distinguish between painted drywall vs concrete vs brick vs other materials + - Note surface treatment: smooth paint vs textured vs raw vs polished + - Document finish: matte vs glossy vs satin + - Identify any surface features: water stains, streaks, cracks, patches, wear + - Assess condition: pristine residential vs industrial weathered vs aged + - Document floor type, color, pattern + - Specify distance/depth layer for each element + - Note condition and state of objects (new/worn/vintage/thriving/wilted) + - Describe any text, artwork, or decorative elements + - Include architectural features (windows, doors, molding, fixtures, frames) +- **Lighting Analysis (CRITICAL)**: + - Distinguish between dramatic directional lighting vs flat even lighting + - Assess directionality: highly directional (strong shadows) vs diffused (soft minimal shadows) + - Document shadow characteristics: harsh defined edges vs soft gradual edges vs minimal + - Note contrast ratio: high contrast (dramatic) vs low contrast (flat) + - Identify if ambient fill light is present reducing shadow depth + - Describe how light sculpts the subject vs evenly illuminates + - Document cast shadows from objects (like plants) on walls + - Note shadow density: deep black vs gray vs faint +- Analyze primary subject and positioning (but NOT face, hair, or identity features) +- Assess scale and framing choices +- Describe subject-background relationship +- Note any secondary subjects or supporting elements + +### Generation Parameters +- Create actionable technical prompts for recreation +- Extract relevant keywords for searchability +- Recommend technical settings for similar results +- Describe post-processing techniques applied + +## Output Requirements +- **Format**: Valid JSON only +- **No markdown**: No ```json``` blocks, no backticks +- **No commentary**: No explanatory text before/after JSON +- **No instructions**: No "Here is your analysis" or "Copy this" +- **Clean structure**: Properly formatted, parseable JSON +- **Single object**: Return one complete JSON analysis object +- **Comprehensive**: All sections must be populated with detailed analysis +- **Specific**: Use precise technical terminology, not vague descriptions +- **Actionable**: Generation parameters must be detailed enough for recreation + +## Processing Logic +1. Analyze the provided image comprehensively across all categories +2. Extract technical specifications and artistic elements +3. Generate recreation prompts and parameters +4. Output single, complete JSON object + +## Quality Standards +- **Confidence score**: Honest assessment of analysis certainty +- **Hex codes**: Approximate but reasonable color values +- **Specific descriptions**: Avoid generic terms like "nice" or "good" +- **Technical accuracy**: Use correct terminology for medium and technique +- **Completeness**: Every JSON field must contain meaningful analysis +- **Actionability**: Prompts and keywords must be specific enough to recreate style + +### CRITICAL Accuracy Requirements: + +**CRITICAL EXCLUSION — Face Structure & Hair:** +- Do NOT include any hair fields (length, cut, texture, styling, part, volume, details, color) +- Do NOT describe face structure, skin tone, eye color, hair color, or any identity-defining features +- These are controlled by separate face reference images and must be omitted entirely +- EXCEPTION: DO include facial_expression fields (mouth position, smile intensity, eye gaze, eyebrow position, emotion, authenticity) — expressions must be captured from the analyzed image + +**Hand & Gesture Description Must Include:** +- Position of BOTH hands (even if one is hidden) +- Exact finger configurations +- For clasped hands: interlacing pattern (loose/tight), thumb position, finger overlap +- Hand tension assessment (relaxed vs tense) +- What hands are interacting with +- Natural vs posed quality with specific evidence +- Contact points and pressure +- Overall gesture naturalness assessment + +**Background Description Must Include:** +- Every visible object cataloged with quadrant position +- Plant species identification (not just "plant") +- Wall material distinction (painted drywall vs concrete vs brick - THIS IS CRITICAL) +- Wall surface treatment (smooth paint vs raw concrete vs textured) +- Wall finish (matte vs glossy) and condition (pristine vs weathered vs industrial) +- Any surface features: water stains, vertical streaks, cracks, patches +- Floor materials with exact colors +- Spatial depth layers (foreground/mid/background) for each element +- Object conditions and states +- Architectural features +- Text or decorative elements + +**Lighting Description Must Include:** +- Directionality assessment (highly directional vs diffused) +- Contrast ratio (high/medium/low) +- Shadow characteristics: edge quality (harsh vs soft), density (deep vs faint), placement +- Cast shadows from objects onto walls +- Presence or absence of ambient fill light +- Whether lighting is dramatic and sculpting vs flat and even +- This distinction is CRITICAL for recreation accuracy + +**Facial Expression (INCLUDE — this is the exception):** +- Exact mouth position (closed smile/slight smile/neutral/serious) +- Smile intensity quantification +- Eye gaze direction and expression +- Eyebrow position +- Overall emotional tone (warm vs neutral vs serious) +- Genuine vs posed quality assessment +- NOTE: Describe the EXPRESSION only, NOT the facial structure (no face shape, no eye color, no skin tone)""" + + +# ---------- Built-in style transfer prompt ---------- + +_STYLE_TRANSFER_PROMPT = r"""You are an expert image editing prompt engineer. Analyze this reference image and extract ALL visual characteristics that should be transferred to another image. Then generate a concise, actionable editing instruction. + +Extract and describe these elements: + +**Subject Appearance:** +- **Clothing**: exact garments, colors, fabrics, fit, style (e.g., "oversized cream knit sweater with a V-neck", "black leather jacket unzipped over a white graphic tee") +- **Pose**: exact body position, angle, weight distribution, hand placement, arm positions, lean direction +- **Facial expression**: exact mouth position (smile type/intensity), eye gaze direction, eyebrow position, overall emotional tone +- **Hair styling**: current style, part, volume, texture state + +**Visual Style:** +- **Lighting**: direction, quality (hard/soft), intensity, color temperature, shadow characteristics +- **Color grading**: overall palette, temperature, saturation, contrast, any color tint or cast +- **Mood/atmosphere**: emotional tone, ambiance +- **Texture/grain**: film grain, noise, smoothness, sharpness +- **Depth of field**: bokeh style, focus +- **Post-processing**: filters, vignetting, bloom, haze, matte look +- **Background**: setting type, colors, blur level, key elements + +Output ONLY the editing instruction as a single paragraph. No explanations, no bullet points, no headers, no markdown. + +Format your output exactly like this example: +"Edit this image so the subject is wearing an oversized cream knit sweater with a V-neck, posed leaning slightly against a wall with their left hand in their pocket and right hand touching their hair, with a relaxed genuine slight smile and direct eye contact, warm golden hour lighting from the left side with soft diffused shadows, desaturated film look with lifted blacks and muted earth tones, subtle film grain, shallow depth of field with a blurred neutral-toned indoor background." + +Be extremely specific about clothing, pose, and expression. The output will be fed directly to an AI image editing model.""" + + +# ---------- Built-in Seedream Edit prompt ---------- + +_SEEDREAM_EDIT_PROMPT = r"""You are Gemini 2.5, an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. +Primary Directive: Your task is to analyze Reference Image 3 (a complete scene) and generate a single, comprehensive prompt for Seedream 4.5. This prompt will instruct the model on how to use a total of three reference images. +Critical Context (Non-negotiable): Seedream will always receive 3 reference images in this specific order: +Images 1 & 2: Provide the subject's complete face structure, facial features, and identity. +Image 3: The complete scene reference (this is the image you will be given to analyze). +Your analysis must focus exclusively on Image 3. Your generated prompt must correctly instruct Seedream on this specific 3-image workflow. +Your Generation Task: +You will be given Image 3. +You will analyze Image 3 ONLY. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. +Mandatory Output Format (Strict Template): +Use the first two reference images for the subject's complete face, features, and identity. Use reference image 3 as the complete reference for all other elements: clothing, pose, action, body type, scene composition, background environment, lighting, and overall atmosphere. +Subject details: [Describe the subject's clothing in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the features.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +_SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT = r"""You are an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. + +Primary Directive: Your task is to analyze all 3 provided images and generate a single, comprehensive prompt for Seedream 4.5. + +Critical Context (Non-negotiable): Seedream will always receive 3 reference images in this specific order: +Images 1 & 2: Provide the subject's complete face structure, facial features, identity, AND body type, body shape, body proportions, skin tone, and any body-specific details such as tattoos, scars, or markings. The output body MUST match these images. +Image 3: The complete scene reference. Provides ONLY the clothing, pose, action, scene composition, background environment, lighting, and overall atmosphere. The body type in Image 3 should be IGNORED — the body must come from Images 1 & 2. + +Your Generation Task: +You will be given all 3 images. +You will analyze Images 1 & 2 for the subject's body proportions and physical build. +You will analyze Image 3 for the scene, clothing, pose, lighting, and atmosphere. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. + +Mandatory Output Format (Strict Template): +Use the first two reference images for the subject's complete face, features, identity, body type, body shape, proportions, skin tone, and any body-specific details such as tattoos or markings. Use reference image 3 as the reference for clothing, pose, action, scene composition, background environment, lighting, and overall atmosphere ONLY — do NOT use image 3 for body type or physique. +Body proportions (from images 1 & 2): [Describe the subject's body proportions in explicit detail as observed in images 1 & 2. Include: overall build (e.g., slim, athletic, curvy, petite, voluptuous), bust/chest size (e.g., small, medium, large, very large), waist (e.g., narrow, thin, wide), hip and butt size (e.g., small, round, wide, large), leg shape (e.g., long, toned, thick), shoulder width, and any other distinctive body features. Be specific and direct — these proportions MUST be preserved in the output regardless of what Image 3's body looks like.] +Subject details: [Describe the subject's clothing from Image 3 in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose from Image 3: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the facial features.] [The body wearing these clothes must match images 1 & 2's body proportions exactly. Any tattoos, scars, or markings from images 1 & 2 must be visible on exposed skin and must not appear on top of clothing.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +# ---------- Built-in Seedream Edit (1 face + 1 ref) prompt ---------- + +_SEEDREAM_EDIT_1FACE_PROMPT = r"""You are Gemini 2.5, an expert prompt engineer specializing in the Seedream 4.5 AI model. You create complete, detailed, and technically precise image generation prompts. + +Primary Directive: Your task is to analyze Reference Image 2 (a complete scene) and generate a single, comprehensive prompt for Seedream 4.5. This prompt will instruct the model on how to use a total of two reference images. + +Critical Context (Non-negotiable): Seedream will always receive 2 reference images in this specific order: +Image 1: Provides the subject's complete face structure, facial features, and identity. +Image 2: The complete scene reference (this is the image you will be given to analyze). + +Your analysis must focus exclusively on Image 2. Your generated prompt must correctly instruct Seedream on this specific 2-image workflow. + +Your Generation Task: +You will be given Image 2. +You will analyze Image 2 ONLY. +You will output ONLY the complete, formatted prompt for Seedream. Do not add any conversational preamble, explanation, or text outside the specified format. + +Mandatory Output Format (Strict Template): +Use reference image 1 for the subject's complete face, features, and identity. Use reference image 2 as the complete reference for all other elements: clothing, pose, action, body type, scene composition, background environment, lighting, and overall atmosphere. +Subject details: [Describe the subject's clothing in exhaustive detail: every visible garment (e.g., shirt, jacket, trousers, dress), accessories (e.g., hat, scarf, belt, bag), jewelry (e.g., necklace, earrings, rings, watch), and footwear. Specify colors, patterns, textures (e.g., denim, silk, wool, leather), cuts (e.g., loose-fitting, tailored), and styles (e.g., formal, casual, athletic)]. [Describe the exact pose: sitting, standing, leaning. Detail the position of the torso, arms (e.g., folded, extended, one hand in pocket), legs (e.g., crossed, straight), and head (e.g., tilted, looking forward)]. [Describe the subject's action or gesture (e.g., holding a cup, pointing, walking, reading) and overall body language. Describe the facial expression type (e.g., a wide smile, a serious expression, a thoughtful look, a laugh) but NOT the features.] +The scene: [Describe the location type (e.g., a city street, a living room, a forest, an office)]. The environment features [describe all significant background and foreground elements: architectural details (e.g., buildings, windows, walls), furniture (e.g., chairs, tables, lamps), props (e.g., books, plants, cars), and natural elements (e.g., trees, mountains, water)]. The setting is [describe the spatial layout, e.g., "indoors in a cluttered studio," "outdoors on a crowded beach"]. +Lighting: [Describe the lighting in technical detail: identify the primary light source(s) (e.g., sun, studio softbox, window, lamp), its direction (e.g., side-lit, backlit, overhead, three-point lighting), its quality (e.g., hard, soft, diffused), and the resulting shadows (e.g., long and soft, sharp and deep). Note the time of day (e.g., golden hour, midday, night) and the overall color temperature (e.g., warm, cool, neutral).] +Camera: [Describe the camera's properties: the angle (e.g., eye-level, low-angle, high-angle, dutch angle), the shot type (e.g., full-body shot, medium shot, cowboy shot), the depth of field (e.g., shallow with heavy bokeh, deep with everything in focus), and the overall composition (e.g., rule of thirds, centered, leading lines).] +Atmosphere: [Describe the mood or ambiance of the scene (e.g., serene, chaotic, melancholic, energetic, professional, mysterious). If outdoors, note weather conditions (e.g., sunny, overcast, rainy, foggy) or environmental effects (e.g., lens flare, mist).] +Colors and textures: [Describe the dominant color palette of the entire image (e.g., monochrome with a blue tint, vibrant analogous colors, muted complementary colors). Highlight key materials and their surface textures (e.g., smooth glass, rough brick, shiny metal, matte fabric, glossy paint).] +Technical quality: [Describe the image's perceived technical quality: resolution feel (e.g., crisp and high-resolution), noise level (e.g., clean, slight grain), and overall rendering style (e.g., photorealistic, painterly, cinematic).]""" + + +_SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT = r"""You are an expert at creating complete image generation prompts for Seedream 4.0 AI model. + +IMPORTANT CONTEXT: +- Seedream will receive 5 reference images in this order: + 1. Images 1-2: Face structure references + 2. Images 3-4: Body type and physique references + 3. Image 5: THIS image - complete scene reference +- You are analyzing image 5 ONLY +- Your output must be a COMPLETE prompt for Seedream + +YOUR TASK: +Analyze this image and create a complete Seedream prompt that instructs the AI how to use all references and describes everything visible in THIS image. + +OUTPUT FORMAT (mandatory structure): +"Use the first two reference images for the face structure. Use reference images 3-4 for the body type and physique. Use reference image 5 as the complete reference for clothing, pose, action, scene composition, background environment, lighting setup, and overall atmosphere. + +Subject details: [Describe the person's clothing in complete detail - every garment, accessories, jewelry, shoes, specific details like patterns, textures, colors, cuts, styles]. [Describe the exact pose - standing, sitting, body position, arm placement, leg position]. [Describe what the person is doing - their action, gesture, body language, facial expression like smiling/serious but WITHOUT describing facial features]. + +The scene: [describe location type and setting]. The environment features [describe architectural elements, furniture, props, and background in detail]. The setting is [indoor/outdoor details with spatial relationships]. + +Lighting: [describe light source, direction, quality, shadows, time of day, color temperature in technical detail]. + +Camera: [describe perspective, depth of field, focal distance, composition. For camera angle: default to 'eye-level' unless the angle is clearly extreme. If the camera is only slightly below eye level, describe it as 'approximately eye-level with a very subtle upward perspective.' If slightly above, use 'approximately eye-level, tilted marginally downward.' Always understate the angle by one level to compensate for Seedream's tendency to exaggerate]. + +Atmosphere: [describe mood, ambiance, weather if applicable, environmental effects]. + +Colors and textures: [describe dominant colors throughout the scene, materials, surface properties, color palette]. + +Technical quality: [high-resolution, sharp focus, professional photography, etc.]." + +CRITICAL RULES: +- DO describe: clothing (every detail), pose, action, body language, gesture, expression type (smile/serious) +- NEVER describe: hair color, hair style, eye color, facial features, skin tone, ethnic features +- Use "this person", "the subject" when referring to the individual +- Be extremely detailed about clothing and accessories +- Be precise about pose and body position +- Focus on EVERYTHING visible except facial/hair features +- CAMERA ANGLE DAMPENING: Seedream heavily amplifies camera angle descriptions. Always understate angles by one full level. Near eye-level → "eye-level." Slightly low → "approximately eye-level with a very subtle upward perspective." Moderately low → "slightly below eye-level." Only use "low angle" if the camera is clearly at knee height or below. Same rule applies upward. +- BANNED CAMERA TERMS: Never use "low-angle shot," "worm's-eye view," "looking up at," "shot from below," or "high-angle shot" unless the source image shows a genuinely extreme perspective. Prefer neutral terms like "eye-level," "approximately eye-level," or "slightly adjusted." + +Output ONLY the formatted prompt, nothing else.""" + + +# ---------- Vertex AI helpers ---------- + +def _ensure_google_auth() -> bool: + try: + import google.oauth2.service_account + return True + except ImportError: + print("📦 [Vertex AI] google-auth non trouvé — installation en cours...") + try: + subprocess.check_call([ + sys.executable, "-m", "pip", "install", + "google-auth", "google-auth-httplib2", "--quiet" + ]) + print("✅ [Vertex AI] google-auth installed successfully!") + return True + except subprocess.CalledProcessError as e: + print(f"❌ [Vertex AI] Failed to install google-auth: {e}") + return False + + +def _load_vertex_credentials(json_path: str): + if not _ensure_google_auth(): + raise RuntimeError("❌ Unable to install google-auth.") + from google.oauth2 import service_account + json_path = json_path.strip() + if not json_path: + raise ValueError("❌ Vertex AI JSON file path is empty.") + if not os.path.isfile(json_path): + raise FileNotFoundError(f"❌ Vertex AI JSON file not found: {json_path}") + try: + with open(json_path, "r", encoding="utf-8") as f: + sa_data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"❌ Invalid JSON file: {e}") + required_fields = ["type", "project_id", "private_key", "client_email"] + missing = [field for field in required_fields if field not in sa_data] + if missing: + raise ValueError(f"❌ Incomplete JSON file — missing fields: {missing}") + if sa_data.get("type") != "service_account": + raise ValueError(f"❌ Unsupported credentials type: '{sa_data.get('type')}'") + scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/generative-language", + ] + credentials = service_account.Credentials.from_service_account_file( + json_path, scopes=scopes + ) + project_id = sa_data.get("project_id", "") + print(f"✅ [Vertex AI] Credentials loaded — project: {project_id}") + return credentials, project_id + + +# ---------- Serve prompts to frontend ---------- + +try: + from server import PromptServer + from aiohttp import web + + @PromptServer.instance.routes.get("/ofm_prompt_generator/get_prompts") + async def _get_prompts(request): + return web.json_response({ + "JSON Image Analysis": _JSON_ANALYSIS_PROMPT, + "Style Transfer Prompt": _STYLE_TRANSFER_PROMPT, + "Seedream Edit (2 face + 1 ref)": _SEEDREAM_EDIT_PROMPT, + "Seedream Edit (1 face + 1 ref)": _SEEDREAM_EDIT_1FACE_PROMPT, + "Seedream Edit (2 face and body + 1 ref)": _SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT, + "Seedream Edit (2 faces + 2 bodies + 1ref)": _SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT, + "Custom Prompt": "", + }) +except Exception: + logging.warning("OFM Prompt Generator: could not register API routes (server not available)") + + +# ---------- Image encoding helper ---------- + +def _image_tensor_to_parts(images): + """Convert ComfyUI IMAGE tensor [B, H, W, C] to Gemini inlineData parts.""" + parts = [] + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype(np.uint8) + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + parts.append({"inlineData": {"mimeType": "image/png", "data": b64}}) + return parts + + +def _strip_markdown_fences(text): + """Remove markdown code fences like ```json ... ``` from the response.""" + text = re.sub(r'^```\w*\s*\n?', '', text) + text = re.sub(r'\n?```\s*$', '', text) + return text.strip() + + +# ---------- Node ---------- + +class GeminiPromptNode: + """OFM Prompt Generator — analyze images or generate prompts with Gemini.""" + + # Cache last known good API keys to survive auto-queue serialization drops + _cached_gemini_key = "" + _cached_grok_key = "" + _cached_vertex_path = "" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "mode": (_PROMPT_MODES, {"default": "JSON Image Analysis"}), + "provider": (_PROVIDERS, {"default": "Gemini"}), + "gemini_api_key": ("STRING", {"default": "", "multiline": False}), + "grok_api_key": ("STRING", {"default": "", "multiline": False}), + }, + "optional": { + "images": ("IMAGE",), + "custom_prompt": ("STRING", { + "default": "", + "multiline": True, + }), + "vertex_json_path": ("STRING", { + "default": "", + "multiline": False, + "tooltip": "Path to the Vertex AI service account JSON file (Vertex provider only)", + }), + "gemini_model": (_GEMINI_MODELS, {"default": "gemini-2.5-pro"}), + "grok_model": (_GROK_MODELS, {"default": "grok-4.20-0309-reasoning"}), + "temperature": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}), + "max_tokens": ("INT", {"default": 8192, "min": 64, "max": 65536, "step": 64}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFF}), + }, + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("prompt",) + FUNCTION = "generate" + OUTPUT_NODE = True + CATEGORY = "utils" + + @classmethod + def IS_CHANGED(cls, **kwargs): + return float("nan") + + def generate(self, mode, provider="Gemini", gemini_api_key="", grok_api_key="", + images=None, custom_prompt="", + vertex_json_path="", + gemini_model="gemini-2.5-pro", grok_model="grok-3", + temperature=1.0, max_tokens=8192, + seed=0): + # Update cache when keys are provided, fall back to cache when empty + if gemini_api_key.strip(): + GeminiPromptNode._cached_gemini_key = gemini_api_key.strip() + if grok_api_key.strip(): + GeminiPromptNode._cached_grok_key = grok_api_key.strip() + if vertex_json_path.strip(): + GeminiPromptNode._cached_vertex_path = vertex_json_path.strip() + + gemini_api_key = gemini_api_key.strip() or GeminiPromptNode._cached_gemini_key + grok_api_key = grok_api_key.strip() or GeminiPromptNode._cached_grok_key + vertex_json_path = vertex_json_path.strip() or GeminiPromptNode._cached_vertex_path + + logging.info("OFM Prompt Generator: provider=%s, gemini_key_len=%d, grok_key_len=%d", + provider, len(gemini_api_key), len(grok_api_key)) + if provider == "Gemini": + api_key = gemini_api_key + if not api_key: + raise RuntimeError("OFM Prompt Generator: Gemini API key is required.") + elif provider == "Vertex": + api_key = "" + if not vertex_json_path.strip(): + raise RuntimeError("OFM Prompt Generator: vertex_json_path is required for the Vertex provider.") + else: + api_key = grok_api_key + if not api_key: + raise RuntimeError("OFM Prompt Generator: Grok API key is required.") + + # Pick the prompt based on mode + if mode == "JSON Image Analysis": + instruction = _JSON_ANALYSIS_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: an image is required for JSON Image Analysis mode.") + elif mode == "Style Transfer Prompt": + instruction = _STYLE_TRANSFER_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image is required for Style Transfer Prompt mode.") + elif mode == "Seedream Edit (2 face + 1 ref)": + instruction = _SEEDREAM_EDIT_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 3 - the scene) is required for Seedream Edit mode.") + elif mode == "Seedream Edit (1 face + 1 ref)": + instruction = _SEEDREAM_EDIT_1FACE_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 2 - the scene) is required for Seedream Edit mode.") + elif mode == "Seedream Edit (2 face and body + 1 ref)": + instruction = _SEEDREAM_EDIT_2FACE_BODY_1REF_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 3 - the scene) is required for Seedream Edit (2 face and body + 1 ref) mode.") + elif mode == "Seedream Edit (2 faces + 2 bodies + 1ref)": + instruction = _SEEDREAM_EDIT_2FACES_2BODIES_1REF_PROMPT + if images is None: + raise RuntimeError("OFM Prompt Generator: a reference image (Image 5 - the scene) is required for Seedream Edit (2 faces + 2 bodies + 1ref) mode.") + else: + instruction = custom_prompt.strip() + if not instruction: + raise RuntimeError("OFM Prompt Generator: custom_prompt cannot be empty in Custom Prompt mode.") + + if provider == "Grok": + text = self._call_grok(api_key, grok_model, instruction, images, temperature, max_tokens) + elif provider == "Vertex": + text = self._call_vertex(vertex_json_path, gemini_model, instruction, images, temperature, max_tokens) + else: + text = self._call_gemini(api_key, gemini_model, instruction, images, temperature, max_tokens) + + text = _strip_markdown_fences(text) + + # Prepend face-preservation instruction for JSON Image Analysis mode + if mode == "JSON Image Analysis": + face_prefix = ( + "Generate a high-quality photograph using ONLY the face and skin tone from reference image 1. " + "Use reference image 2 as the visual reference for everything else: hair, clothing, pose, body positioning, " + "styling, lighting, composition, background, color palette, mood, and all other visual details. " + "The following JSON analysis is a detailed breakdown of reference image 2 — follow it precisely:\n" + ) + text = face_prefix + text + + active_model = grok_model if provider == "Grok" else gemini_model + logging.info("OFM Prompt Generator: generated %d chars with %s", len(text), active_model) + return {"ui": {"text": [text]}, "result": (text,)} + + def _call_gemini(self, api_key, model, instruction, images, temperature, max_tokens): + url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}" + + parts = [] + if images is not None: + parts.extend(_image_tensor_to_parts(images)) + parts.append({"text": instruction}) + + payload = { + "contents": [{"parts": parts}], + "generationConfig": { + "temperature": temperature, + "maxOutputTokens": max_tokens, + }, + } + + try: + resp = requests.post(url, json=payload, + headers={"Content-Type": "application/json"}, + timeout=180) + resp.raise_for_status() + data = resp.json() + except requests.exceptions.HTTPError as e: + msg = f"OFM Prompt Generator API error: {e.response.status_code}" + try: + body = e.response.json() + if "error" in body: + msg += f" — {body['error']}" + except Exception: + msg += f" — {e.response.text[:200]}" + raise RuntimeError(msg) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"OFM Prompt Generator request error: {e!s}") + + text = _extract_text(data) + if not text: + raise RuntimeError(f"OFM Prompt Generator: no text in response. {_response_summary(data)}") + return text + + def _call_vertex(self, json_path, model, instruction, images, temperature, max_tokens): + from google import genai + from google.genai import types + + credentials, project_id = _load_vertex_credentials(json_path) + print(f"\U0001f310 [Vertex AI] Connexion \u2014 projet={project_id} | location=us-central1 | mod\u00e8le={model}") + + client = genai.Client( + vertexai=True, + project=project_id, + location="us-central1", + credentials=credentials, + ) + + contents = [] + if images is not None: + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype("uint8") + pil = Image.fromarray(img_np) + contents.append(pil) + contents.append(instruction) + + config = types.GenerateContentConfig( + temperature=temperature, + max_output_tokens=max_tokens, + ) + + try: + response = client.models.generate_content( + model=model, + contents=contents, + config=config, + ) + except Exception as e: + raise RuntimeError(f"OFM Prompt Generator (Vertex) erreur API : {e}") + + text = "" + try: + for part in response.candidates[0].content.parts: + if getattr(part, "thought", False): + continue + if hasattr(part, "text") and part.text: + text += part.text + except Exception: + pass + if not text: + try: + text = response.text or "" + except Exception: + pass + if not text: + raise RuntimeError("OFM Prompt Generator (Vertex) : aucun texte dans la r\u00e9ponse.") + return text.strip() + + def _call_grok(self, api_key, grok_model, instruction, images, temperature, max_tokens): + url = "https://api.x.ai/v1/chat/completions" + + # Build message content + content = [] + if images is not None: + for i in range(images.shape[0]): + img_np = (255.0 * images[i].cpu().numpy()).clip(0, 255).astype("uint8") + pil = Image.fromarray(img_np) + buf = io.BytesIO() + pil.save(buf, format="PNG") + b64 = base64.b64encode(buf.getvalue()).decode("ascii") + content.append({ + "type": "image_url", + "image_url": {"url": f"data:image/png;base64,{b64}"}, + }) + content.append({"type": "text", "text": instruction}) + + payload = { + "model": grok_model, + "messages": [{"role": "user", "content": content}], + "temperature": temperature, + "max_completion_tokens": max_tokens, + } + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + } + + try: + resp = requests.post(url, json=payload, headers=headers, timeout=180) + resp.raise_for_status() + data = resp.json() + except requests.exceptions.HTTPError as e: + msg = f"OFM Prompt Generator (Grok) API error: {e.response.status_code}" + try: + body = e.response.json() + if "error" in body: + msg += f" \u2014 {body['error']}" + except Exception: + msg += f" \u2014 {e.response.text[:200]}" + raise RuntimeError(msg) + except requests.exceptions.RequestException as e: + raise RuntimeError(f"OFM Prompt Generator (Grok) request error: {e!s}") + + choices = data.get("choices", []) + if not choices: + raise RuntimeError("OFM Prompt Generator (Grok): no choices in API response.") + text = choices[0].get("message", {}).get("content", "") + if not text: + raise RuntimeError("OFM Prompt Generator (Grok): empty response from API.") + return text + + +def _extract_text(data): + """Extract concatenated text from Gemini response, skipping thought parts.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + return None + parts = candidates[0].get("content", {}).get("parts") or [] + texts = [] + for part in parts: + if part.get("thought"): + continue + if "text" in part: + texts.append(part["text"]) + return "\n".join(texts).strip() if texts else None + except (KeyError, TypeError): + return None + + +def _response_summary(data): + """Summarize why the response had no usable text.""" + try: + candidates = data.get("candidates") or [] + if not candidates: + block = data.get("promptFeedback", {}).get("blockReason", "") + if block: + return f"Prompt blocked: {block}" + return "No candidates returned." + reason = candidates[0].get("finishReason", "") + return f"finishReason={reason}" + except Exception: + return "" diff --git a/aiorbust-ofm-pack-main/image_processing.py b/aiorbust-ofm-pack-main/image_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..4868ab14e78d8c7d8b19523779b428f79c9a0e86 --- /dev/null +++ b/aiorbust-ofm-pack-main/image_processing.py @@ -0,0 +1,323 @@ +""" +ComfyUI nodes for image post-processing. +- Remove Image Metadata: strip all metadata and re-save as clean JPEG +- Save as Phone Photo: re-save with realistic phone camera EXIF +""" + +import logging +import os +import math +import random +from datetime import datetime, timedelta + +import numpy as np +from PIL import Image +from PIL.ExifTags import IFD +from PIL.TiffImagePlugin import IFDRational +import folder_paths + + +# ---------- Directory helpers ---------- + +_VALID_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp"} + + +def _load_images_from_folder(folder): + """Load all images from a subfolder under ComfyUI's input directory.""" + input_dir = os.path.join(folder_paths.get_input_directory(), folder) + if not os.path.isdir(input_dir): + raise RuntimeError(f"Folder not found: {input_dir}") + files = sorted( + f for f in os.listdir(input_dir) + if os.path.splitext(f)[1].lower() in _VALID_IMAGE_EXTENSIONS + ) + if not files: + raise RuntimeError(f"No images found in {input_dir}") + images = [] + for f in files: + img = Image.open(os.path.join(input_dir, f)).convert("RGB") + images.append((f, img)) + return images + + +# ---------- Remove Image Metadata ---------- + +class MetadataRemoveNode: + """Batch-strip all metadata from images in a folder (EXIF, XMP, PNG chunks, ICC, C2PA).""" + + def __init__(self): + self.type = "output" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "folder": (folder_paths.get_input_subfolders(),), + "filename_prefix": ("STRING", {"default": "ComfyUI"}), + "output_folder": ("STRING", {"default": "cleaned"}), + "quality": ("INT", {"default": 93, "min": 1, "max": 100, "step": 1}), + }, + "optional": { + "add_noise": ("BOOLEAN", {"default": True}), + }, + } + + RETURN_TYPES = () + FUNCTION = "remove_metadata" + OUTPUT_NODE = True + CATEGORY = "image" + + def remove_metadata(self, folder, filename_prefix="ComfyUI", output_folder="cleaned", quality=93, add_noise=True): + source_images = _load_images_from_folder(folder) + out_dir = os.path.join(folder_paths.get_output_directory(), output_folder) + os.makedirs(out_dir, exist_ok=True) + subfolder = output_folder + + results = [] + for counter, (orig_name, img) in enumerate(source_images, start=1): + img_np = np.array(img).astype(np.uint8) + if add_noise: + noise = np.random.choice([-1, 0, 1], size=img_np.shape).astype(np.int16) + img_np = np.clip(img_np.astype(np.int16) + noise, 0, 255).astype(np.uint8) + clean = Image.fromarray(img_np, mode="RGB") + + out_name = f"{filename_prefix}_{counter:05d}.jpg" + clean.save(os.path.join(out_dir, out_name), "JPEG", quality=quality) + results.append({"filename": out_name, "subfolder": subfolder, "type": self.type}) + + logging.info("MetadataRemoveNode: processed %d images from '%s' -> output/%s", len(results), folder, output_folder) + return {"ui": {"images": results}} + + +# ---------- Save as Phone Photo ---------- + +_PHONE_PROFILES = { + "iPhone 15 Pro Max": { + "make": "Apple", "model": "iPhone 15 Pro Max", + "software": "17.5.1", + "focal_length": (6765, 1000), "f_number": (178, 100), + "iso_range": (50, 800), "exposure_range": (1, 4000), + "lens_model": "iPhone 15 Pro Max back triple camera 6.765mm f/1.78", + "resolutions": {"12MP": (4032, 3024), "48MP": (8064, 6048)}, + }, + "iPhone 16 Pro Max": { + "make": "Apple", "model": "iPhone 16 Pro Max", + "software": "18.3.1", + "focal_length": (6765, 1000), "f_number": (178, 100), + "iso_range": (50, 1600), "exposure_range": (1, 4000), + "lens_model": "iPhone 16 Pro Max back quad camera 6.765mm f/1.78", + "resolutions": {"12MP": (4032, 3024), "48MP": (8064, 6048)}, + }, + "Samsung Galaxy S24 Ultra": { + "make": "samsung", "model": "SM-S928B", + "software": "S928BXXS4AXL1", + "focal_length": (6300, 1000), "f_number": (170, 100), + "iso_range": (50, 800), "exposure_range": (1, 3000), + "lens_model": "SM-S928B", + "resolutions": {"12MP": (4000, 3000), "50MP": (8160, 6120)}, + }, + "Samsung Galaxy S25 Ultra": { + "make": "samsung", "model": "SM-S938B", + "software": "S938BXXU1AXK5", + "focal_length": (6300, 1000), "f_number": (170, 100), + "iso_range": (50, 1000), "exposure_range": (1, 4000), + "lens_model": "SM-S938B", + "resolutions": {"12MP": (4000, 3000), "50MP": (8160, 6120)}, + }, +} + +_PHONE_CHOICES = list(_PHONE_PROFILES.keys()) + +_RESOLUTION_CHOICES = ["12MP", "48MP/50MP", "Original"] + +_GPS_LOCATIONS = { + "None": None, + "New York": (40.7128, -74.0060, 10), + "Los Angeles": (34.0522, -118.2437, 71), + "London": (51.5074, -0.1278, 11), + "Tokyo": (35.6762, 139.6503, 40), + "Paris": (48.8566, 2.3522, 35), + "Sydney": (-33.8688, 151.2093, 58), + "Dubai": (25.2048, 55.2708, 5), + "Random US City": "random", +} + +_RANDOM_US_CITIES = [ + (40.7128, -74.0060, 10), # New York + (34.0522, -118.2437, 71), # Los Angeles + (41.8781, -87.6298, 181), # Chicago + (29.7604, -95.3698, 15), # Houston + (33.4484, -112.0740, 331), # Phoenix + (29.4241, -98.4936, 198), # San Antonio + (32.7157, -117.1611, 20), # San Diego + (30.2672, -97.7431, 149), # Austin + (37.7749, -122.4194, 16), # San Francisco + (47.6062, -122.3321, 56), # Seattle + (39.7392, -104.9903, 1609), # Denver + (35.2271, -80.8431, 229), # Charlotte + (36.1627, -86.7816, 182), # Nashville + (25.7617, -80.1918, 2), # Miami + (38.9072, -77.0369, 22), # Washington DC +] + +_GPS_CHOICES = list(_GPS_LOCATIONS.keys()) + + +def _decimal_to_dms(decimal_deg): + """Convert decimal degrees to (degrees, minutes, seconds) as IFDRational tuples.""" + d = abs(decimal_deg) + degrees = int(d) + minutes = int((d - degrees) * 60) + seconds = round((d - degrees - minutes / 60) * 3600 * 100) + return (IFDRational(degrees, 1), IFDRational(minutes, 1), IFDRational(seconds, 100)) + + +def _build_phone_exif(profile, width, height, gps_coords=None): + """Build EXIF bytes mimicking a phone camera shot.""" + now = datetime.now() - timedelta(seconds=random.randint(0, 300)) + dt_str = now.strftime("%Y:%m:%d %H:%M:%S") + + iso = random.randint(profile["iso_range"][0], profile["iso_range"][1]) + exp_denom = random.randint(profile["exposure_range"][0], profile["exposure_range"][1]) + ssv_num = int(round(math.log2(exp_denom) * 100)) + ssv = (ssv_num, 100) + + exif = Image.Exif() + # IFD0 + exif[0x010F] = profile["make"] + exif[0x0110] = profile["model"] + exif[0x0112] = 1 # Orientation: normal + exif[0x011A] = 72 # XResolution + exif[0x011B] = 72 # YResolution + exif[0x0128] = 2 # ResolutionUnit: inches + exif[0x0131] = profile["software"] + exif[0x0132] = dt_str + exif[0x0213] = 1 # YCbCrPositioning: centered + + # Exif sub-IFD + exif_ifd = exif.get_ifd(IFD.Exif) + exif_ifd[0x829A] = (1, exp_denom) # ExposureTime + exif_ifd[0x829D] = profile["f_number"] # FNumber + exif_ifd[0x8822] = 2 # ExposureProgram: normal + exif_ifd[0x8827] = iso # ISOSpeedRatings + exif_ifd[0x9000] = b"0232" # ExifVersion + exif_ifd[0x9003] = dt_str # DateTimeOriginal + exif_ifd[0x9004] = dt_str # DateTimeDigitized + exif_ifd[0x9201] = ssv # ShutterSpeedValue (APEX) + exif_ifd[0x9202] = profile["f_number"] # ApertureValue + exif_ifd[0x9203] = (0, 1) # BrightnessValue + exif_ifd[0x9204] = (0, 1) # ExposureBiasValue + exif_ifd[0x9207] = 5 # MeteringMode: pattern + exif_ifd[0x9209] = 0x10 # Flash: no flash + exif_ifd[0x920A] = profile["focal_length"] # FocalLength + exif_ifd[0xA001] = 1 # ColorSpace: sRGB + exif_ifd[0xA002] = width # PixelXDimension + exif_ifd[0xA003] = height # PixelYDimension + exif_ifd[0xA405] = 26 # FocalLengthIn35mmFilm (~26mm equiv) + exif_ifd[0xA406] = 0 # SceneCaptureType: standard + exif_ifd[0xA433] = profile["make"] # LensMake + exif_ifd[0xA434] = profile["lens_model"] # LensModel + + # GPS IFD + if gps_coords: + lat, lon, alt = gps_coords + # Add slight random jitter (±0.001° ≈ ±100m) + lat += random.uniform(-0.001, 0.001) + lon += random.uniform(-0.001, 0.001) + + gps_ifd = exif.get_ifd(IFD.GPSInfo) + gps_ifd[0] = b"\x02\x03\x00\x00" # GPSVersionID + gps_ifd[1] = "N" if lat >= 0 else "S" # GPSLatitudeRef + gps_ifd[2] = _decimal_to_dms(lat) # GPSLatitude + gps_ifd[3] = "E" if lon >= 0 else "W" # GPSLongitudeRef + gps_ifd[4] = _decimal_to_dms(lon) # GPSLongitude + gps_ifd[5] = 0 # GPSAltitudeRef: above sea level + gps_ifd[6] = IFDRational(int(alt * 100), 100) # GPSAltitude + gps_ifd[7] = (IFDRational(now.hour, 1), IFDRational(now.minute, 1), IFDRational(now.second, 1)) # GPSTimeStamp + gps_ifd[29] = now.strftime("%Y:%m:%d") # GPSDateStamp + + return exif.tobytes() + + +class SaveAsPhonePhotoNode: + """Batch-save images from a folder as JPEG with realistic phone camera EXIF metadata.""" + + def __init__(self): + self.type = "output" + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "folder": (folder_paths.get_input_subfolders(),), + "filename_prefix": ("STRING", {"default": "ComfyUI"}), + "phone_model": (_PHONE_CHOICES,), + "resolution": (_RESOLUTION_CHOICES, {"default": "12MP"}), + "gps_location": (_GPS_CHOICES, {"default": "Random US City"}), + "output_folder": ("STRING", {"default": "phone_photos"}), + "quality": ("INT", {"default": 95, "min": 1, "max": 100, "step": 1}), + }, + "optional": { + "add_noise": ("BOOLEAN", {"default": True}), + }, + } + + RETURN_TYPES = () + FUNCTION = "save_phone_photo" + OUTPUT_NODE = True + CATEGORY = "image" + + def save_phone_photo(self, folder, filename_prefix="ComfyUI", phone_model="iPhone 15 Pro Max", resolution="12MP", gps_location="Random US City", + output_folder="phone_photos", quality=95, add_noise=True): + source_images = _load_images_from_folder(folder) + out_dir = os.path.join(folder_paths.get_output_directory(), output_folder) + os.makedirs(out_dir, exist_ok=True) + subfolder = output_folder + + profile = _PHONE_PROFILES[phone_model] + + # Resolve GPS coordinates + gps_coords = None + gps_val = _GPS_LOCATIONS.get(gps_location) + if gps_val == "random": + gps_coords = random.choice(_RANDOM_US_CITIES) + elif gps_val is not None: + gps_coords = gps_val + + # Resolve target resolution + target_size = None + if resolution != "Original": + res_map = profile["resolutions"] + if resolution == "12MP": + target_size = res_map.get("12MP") + elif resolution == "48MP/50MP": + target_size = res_map.get("48MP") or res_map.get("50MP") + + results = [] + for counter, (orig_name, img) in enumerate(source_images, start=1): + # Resize to phone resolution if needed + if target_size: + src_w, src_h = img.size + tgt_w, tgt_h = target_size + # Match orientation: if source is portrait, swap target to portrait + if src_h > src_w and tgt_w > tgt_h: + tgt_w, tgt_h = tgt_h, tgt_w + elif src_w > src_h and tgt_h > tgt_w: + tgt_w, tgt_h = tgt_h, tgt_w + img = img.resize((tgt_w, tgt_h), Image.LANCZOS) + + img_np = np.array(img).astype(np.uint8) + if add_noise: + noise = np.random.choice([-1, 0, 1], size=img_np.shape).astype(np.int16) + img_np = np.clip(img_np.astype(np.int16) + noise, 0, 255).astype(np.uint8) + + clean = Image.fromarray(img_np, mode="RGB") + w, h = clean.size + exif_bytes = _build_phone_exif(profile, w, h, gps_coords=gps_coords) + + out_name = f"{filename_prefix}_{counter:05d}.jpg" + clean.save(os.path.join(out_dir, out_name), "JPEG", quality=quality, exif=exif_bytes) + results.append({"filename": out_name, "subfolder": subfolder, "type": self.type}) + + logging.info("SaveAsPhonePhotoNode: processed %d images from '%s' -> output/%s", len(results), folder, output_folder) + return {"ui": {"images": results}} diff --git a/aiorbust-ofm-pack-main/js/aiorbust_theme.js b/aiorbust-ofm-pack-main/js/aiorbust_theme.js new file mode 100644 index 0000000000000000000000000000000000000000..b3a105f67622d7549e60b5098b387ee13a11b3b6 --- /dev/null +++ b/aiorbust-ofm-pack-main/js/aiorbust_theme.js @@ -0,0 +1,145 @@ +import { app } from "../../scripts/app.js"; + +// Tous les nodes Aiorbust — thème feu unifié +const ALL_NODES = [ + "NanoBananaProEditAPINode", + "NanoBanana2EditAPINode", + "SeedreamEditAPINode", + "SeedreamEditFalAPINode", + "LoraCaptionGeneratorNode", + "DirectoryImageLoaderNode", + "LoadAPIKeysNode", + "Aiorbust_Api_Loader", + "VideoFrameExtractorNode", + "MetadataRemoveNodeMonthly", + "SaveAsPhonePhotoNodeMonthly", + "Aiorbust_Renoise", + "Aiorbust_Camera_Look", + "Aiorbust_Apply_LUT", + "InstagramFaceSwapNode", + "DatasetCreatorNode", +]; + +function applyFireTheme(node) { + node.color = "#3d2008"; + node.bgcolor = "#1c1209"; + node.boxcolor = "#e87a20"; + node.title_color = "#f5a623"; + const flames = []; + for (let i = 0; i < 35; i++) { + flames.push({ + x: Math.random(), + y: 1.0 + Math.random() * 0.3, + size: Math.random() * 4 + 2, + speed: Math.random() * 0.008 + 0.004, + wobble: Math.random() * 0.003, + phase: Math.random() * Math.PI * 2, + life: Math.random(), + }); + } + function resetFlame(f) { + f.x = Math.random(); + f.y = 1.0 + Math.random() * 0.1; + f.life = 1.0; + f.size = Math.random() * 4 + 2; + f.speed = Math.random() * 0.008 + 0.004; + } + const origDrawForeground = node.onDrawForeground; + node.onDrawForeground = function (ctx) { + if (origDrawForeground) origDrawForeground.call(this, ctx); + const t = performance.now() / 1000; + const w = node.size[0]; + const h = node.size[1]; + // Warm glow border + ctx.save(); + const pulse = 0.3 + Math.sin(t * 2) * 0.15; + ctx.shadowColor = "#e87a20"; + ctx.shadowBlur = 8 + Math.sin(t * 3) * 4; + ctx.strokeStyle = `rgba(232, 122, 32, ${pulse})`; + ctx.lineWidth = 1.5; + ctx.strokeRect(0, 0, w, h); + ctx.restore(); + // Fire gradient accent line + ctx.save(); + const grad = ctx.createLinearGradient(0, 0, w, 0); + const s = (t * 0.5) % 1; + grad.addColorStop(0, "#cc4400"); + grad.addColorStop(Math.abs((s) % 1), "#e87a20"); + grad.addColorStop(Math.abs((s + 0.3) % 1), "#f5a623"); + grad.addColorStop(Math.abs((s + 0.6) % 1), "#ffcc33"); + grad.addColorStop(1, "#cc4400"); + ctx.fillStyle = grad; + ctx.fillRect(0, -1, w, 3); + ctx.restore(); + // Fire embers + ctx.save(); + for (const f of flames) { + f.y -= f.speed; + f.x += Math.sin(t * 3 + f.phase) * f.wobble; + f.life -= f.speed * 0.8; + if (f.life <= 0 || f.y < -0.1) { + resetFlame(f); + continue; + } + const px = f.x * w; + const py = f.y * h; + const life = f.life; + const sz = f.size * life; + let r, g, b; + if (life > 0.7) { + r = 255; g = 200 + (life - 0.7) * 180; b = 50 + (life - 0.7) * 200; + } else if (life > 0.4) { + r = 232; g = 122; b = 32; + } else { + r = 200; g = 60; b = 10; + } + ctx.globalAlpha = life * 0.6; + const glowGrad = ctx.createRadialGradient(px, py, 0, px, py, sz * 3); + glowGrad.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${life * 0.5})`); + glowGrad.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`); + ctx.fillStyle = glowGrad; + ctx.beginPath(); + ctx.arc(px, py, sz * 3, 0, Math.PI * 2); + ctx.fill(); + ctx.globalAlpha = life * 0.9; + ctx.fillStyle = `rgb(${r}, ${g}, ${b})`; + ctx.beginPath(); + ctx.arc(px, py, sz * 0.6, 0, Math.PI * 2); + ctx.fill(); + f.phase += 0.02; + } + ctx.restore(); + // Badge + ctx.save(); + const badgeText = "AIORBUST"; + ctx.font = "bold 9px sans-serif"; + const textWidth = ctx.measureText(badgeText).width; + const badgeX = w - textWidth - 12; + const badgeY = -LiteGraph.NODE_TITLE_HEIGHT + 6; + ctx.fillStyle = "rgba(60, 20, 5, 0.9)"; + ctx.fillRect(badgeX - 4, badgeY - 1, textWidth + 8, 14); + ctx.fillStyle = "#f5a623"; + ctx.fillText(badgeText, badgeX, badgeY + 10); + ctx.restore(); + node.setDirtyCanvas(true, false); + }; +} + +app.registerExtension({ + name: "aiorbust.Theme", + nodeCreated(node) { + if (ALL_NODES.includes(node.comfyClass)) { + applyFireTheme(node); + } + if ( + node.comfyClass === "PreviewImageWithoutMetadata" || + node.comfyClass === "AiorBustVideoLoader" || + node.comfyClass === "NanoBananaAIO" + ) { + node.color = "#3d2008"; + node.bgcolor = "#1c1209"; + node.boxcolor = "#e87a20"; + node.title_color = "#f5a623"; + } + }, +}); \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/js/directory_loader.js b/aiorbust-ofm-pack-main/js/directory_loader.js new file mode 100644 index 0000000000000000000000000000000000000000..2334086603b0ba9934d475035c5d8615f82d72ac --- /dev/null +++ b/aiorbust-ofm-pack-main/js/directory_loader.js @@ -0,0 +1,83 @@ +import { app } from "../../scripts/app.js"; +import { api } from "../../scripts/api.js"; + +app.registerExtension({ + name: "aiorbust.DirectoryImageLoader", + nodeCreated(node) { + if (node.comfyClass !== "DirectoryImageLoaderNode") return; + + const toggleWidget = node.widgets.find(w => w.name === "use_absolute_path"); + const folderWidget = node.widgets.find(w => w.name === "input_folder"); + const pathWidget = node.widgets.find(w => w.name === "absolute_path"); + + if (!toggleWidget || !folderWidget || !pathWidget) return; + + function updateVisibility() { + const useAbsolute = toggleWidget.value; + folderWidget.disabled = useAbsolute; + pathWidget.disabled = !useAbsolute; + } + + updateVisibility(); + + const origCallback = toggleWidget.callback; + toggleWidget.callback = function (...args) { + if (origCallback) origCallback.apply(this, args); + updateVisibility(); + }; + }, + + async setup() { + // Track remaining count from directory loader's output + let pendingRemaining = 0; + let hadError = false; + + // Capture remaining count when directory loader node executes + api.addEventListener("executed", ({ detail }) => { + if (!detail || !detail.output) return; + + const output = detail.output; + if (output.remaining === undefined || output.run_count === undefined) return; + + const remaining = output.remaining[0]; + const current = output.current_index[0]; + const filename = output.filename ? output.filename[0] : ""; + + console.log(`[Directory Loader] Processed ${current + 1}: ${filename}`); + pendingRemaining = remaining; + }); + + // On any error, stop the batch + api.addEventListener("execution_error", () => { + if (pendingRemaining > 0) { + console.warn("[Directory Loader] Error during batch — stopping. " + pendingRemaining + " remaining images skipped."); + fetch("/directory_loader/reset_batch", { method: "POST" }).catch(() => {}); + } + pendingRemaining = 0; + hadError = true; + }); + + // Only auto-queue after the ENTIRE workflow completes successfully + api.addEventListener("status", ({ detail }) => { + // status fires with detail.exec_info.queue_remaining === 0 when idle + if (!detail || !detail.exec_info) return; + if (detail.exec_info.queue_remaining !== 0) return; + + // Workflow just finished — check if we should queue next + if (hadError) { + hadError = false; + pendingRemaining = 0; + return; + } + + if (pendingRemaining > 0) { + console.log(`[Directory Loader] ${pendingRemaining} remaining, auto-queuing next...`); + const rem = pendingRemaining; + pendingRemaining = 0; + setTimeout(() => { + app.queuePrompt(0, 1); + }, 500); + } + }); + }, +}); diff --git a/aiorbust-ofm-pack-main/js/nb_aio_faceswap.js b/aiorbust-ofm-pack-main/js/nb_aio_faceswap.js new file mode 100644 index 0000000000000000000000000000000000000000..7b9ca4e94b1799c83e877c26bb17df29cf82a5fc --- /dev/null +++ b/aiorbust-ofm-pack-main/js/nb_aio_faceswap.js @@ -0,0 +1,1171 @@ +/** + * NanoBananaAIO — Automation Face Swap UI + Image/Video Mode Toggle + * Bloc visuel distinctif avec toggle ON/OFF, verrouillage des widgets, + * restriction du modèle à NBPro/NB2, et option Breast Refiner. + * + Toggle IMAGE / VIDEO avec support Veo 3 (Google & Vertex). + */ +import { app } from "../../scripts/app.js"; +// ─── Constantes mode vidéo ───────────────────────────────────────────────── +const VIDEO_MODELS = ["Veo 3.1 Lite", "Veo 3.1", "Veo 3.1 Fast", "Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control", "Seedance 2.0"]; +const IMAGE_MODELS_DEFAULT = ["Nano Banana Pro", "Nano Banana 2", "Seedream 4.5", "GPT Image 2.0"]; +const VIDEO_ASPECT_RATIOS = ["16:9", "9:16"]; +const IMAGE_ASPECT_RATIOS = ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"]; +const VIDEO_RESOLUTIONS = ["480p", "720p", "1080p", "4K"]; +const KLING30_MODELS = ["Kling 3.0"]; +const IMAGE_RESOLUTIONS = ["1K", "2K", "4K"]; +const SEEDANCE_MODELS = ["Seedance 2.0"]; +// ─── Widgets verrouillés en mode automation ──────────────────────────────── +const LOCKABLE_WIDGETS = [ + "prompt", + "negative_prompt", + "use_search", + "system_instructions", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", +]; +const AUTOMATION_MODELS = ["Nano Banana Pro", "Nano Banana 2"]; +// ─── Helpers ─────────────────────────────────────────────────────────────── +function getWidget(node, name) { + return node.widgets?.find(w => w.name === name); +} +/** Synchronise un widget Python caché avec une valeur JS. */ +function syncNodeWidget(node, name, value) { + const w = getWidget(node, name); + if (w) { + w.value = value; + if (w.callback) w.callback(value); + } +} +/** Masque ou affiche un widget standard (computeSize trick). */ +function setWidgetVisible(node, widgetName, visible) { + const w = getWidget(node, widgetName); + if (!w) return; + if (visible) { + if (w._modeOrigComputeSize !== undefined) { + w.computeSize = w._modeOrigComputeSize; + delete w._modeOrigComputeSize; + } else { + delete w.computeSize; + } + w.disabled = false; + w.hidden = false; + } else { + if (w._modeOrigComputeSize === undefined) { + w._modeOrigComputeSize = w.computeSize; + } + w.computeSize = () => [0, -4]; + w.disabled = true; + w.hidden = true; + } + if (w.inputEl) w.inputEl.style.display = visible ? "" : "none"; + if (w.element) w.element.style.display = visible ? "" : "none"; +} +function setWidgetLocked(node, widgetName, locked) { + const w = getWidget(node, widgetName); + if (!w) return; + w.disabled = locked; + const applyStyle = (el) => { + if (!el || !el.style) return; + el.style.opacity = locked ? "0.3" : "1.0"; + el.style.pointerEvents = locked ? "none" : "auto"; + el.style.filter = locked ? "grayscale(60%)" : "none"; + }; + if (w.inputEl) { + w.inputEl.disabled = locked; + applyStyle(w.inputEl); + // Les widgets multiline (negative_prompt, system_instructions) sont + // wrappés dans un parent
; on applique aussi l'effet dessus. + applyStyle(w.inputEl.parentElement); + } + applyStyle(w.element); +} +/** + * Redirige les événements wheel du container DOM vers le canvas LiteGraph, + * pour que le zoom ComfyUI fonctionne même quand la souris survole un widget DOM. + */ +function forwardWheelToCanvas(el) { + el.addEventListener("wheel", (e) => { + e.preventDefault(); + e.stopPropagation(); + const canvas = app.canvas?.canvas; + if (!canvas) return; + canvas.dispatchEvent(new WheelEvent("wheel", { + bubbles: true, cancelable: true, view: window, + deltaX: e.deltaX, deltaY: e.deltaY, deltaZ: e.deltaZ, deltaMode: e.deltaMode, + clientX: e.clientX, clientY: e.clientY, screenX: e.screenX, screenY: e.screenY, + ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey, metaKey: e.metaKey, + })); + }, { passive: false }); +} +/** + * Applique / retire l'état automation au node (verrouille les widgets + * et restreint la liste des modèles à NBPro/NB2). + */ +function applyAutomationState(node, enabled) { + const applyLocks = () => { + for (const name of LOCKABLE_WIDGETS) setWidgetLocked(node, name, enabled); + }; + // Passe immédiate, puis plusieurs passes différées pour rattraper les + // widgets multiline (negative_prompt, system_instructions) dont l'inputEl + // n'est parfois rattaché au DOM qu'après un ou deux frames. + applyLocks(); + requestAnimationFrame(applyLocks); + setTimeout(applyLocks, 100); + setTimeout(applyLocks, 400); + const modelWidget = getWidget(node, "model"); + if (!modelWidget) return; + if (enabled) { + if (modelWidget.options?.values) { + modelWidget.options.values = [...AUTOMATION_MODELS]; + } + if (!AUTOMATION_MODELS.includes(modelWidget.value)) { + modelWidget.value = "Nano Banana Pro"; + if (modelWidget.callback) modelWidget.callback("Nano Banana Pro"); + } + } else { + // Restaurer la liste selon le mode courant — Python déclare image+vidéo + // donc on ne peut plus se fier à _fsOrigValues comme source de vérité. + const correctModels = node._nbIsVideoMode ? VIDEO_MODELS : IMAGE_MODELS_DEFAULT; + if (modelWidget.options?.values) modelWidget.options.values = [...correctModels]; + // S'assurer que la valeur courante est dans la liste restaurée + if (!correctModels.includes(modelWidget.value)) { + modelWidget.value = correctModels[0]; + if (modelWidget.callback) modelWidget.callback(correctModels[0]); + } + } + modelWidget.disabled = false; + app.graph.setDirtyCanvas(true, true); +} +// ─── Sync aspect_ratio : grisé si Kling (any) + WAVESPEED en mode vidéo ──────── +// KLING_MODELS — conservé pour référence future, plus utilisé pour le verrouillage aspect_ratio +// (Kling supporte 16:9 et 9:16, les deux valeurs de VIDEO_ASPECT_RATIOS) +const KLING_MODELS = ["Kling 3.0", "Kling 2.6", "Kling 3.0 Motion Control"]; +// GPT Image 2.0 — aspect ratios supportés (filtre automatique du dropdown) +const GPT2_ASPECT_RATIOS = ["auto", "1:1", "4:3", "3:4", "16:9", "9:16"]; +const GPT2_NEAREST_AR = { + "2:3": "9:16", "3:2": "16:9", "4:5": "3:4", "5:4": "4:3", "21:9": "16:9", +}; +function setupKlingAspectRatioSync(node) { + // Kling supporte 16:9 ET 9:16 — le dropdown est déjà restreint à VIDEO_ASPECT_RATIOS + // en mode vidéo, donc aucun verrouillage supplémentaire n'est nécessaire. + // La fonction reste en place pour compatibilité avec les appels existants. + node._nbSyncKlingAspectRatio = () => {}; +} +// ─── Contraintes de durée par modèle vidéo ──────────────────────────────────── +const DURATION_CONSTRAINTS = { + "Kling 2.6": { min: 5, max: 10, step: 5, tooltip: "⚠️ Kling 2.6 only supports 5s or 10s. Any other value will be rounded automatically." }, + "Kling 3.0": { min: 3, max: 15, step: 1, tooltip: "" }, + "Kling 3.0 Motion Control": { min: 3, max: 15, step: 1, tooltip: "ℹ️ Motion Control: output duration equals the reference video's duration." }, + "Seedance 2.0": { min: 4, max: 15, step: 1, tooltip: "⚠️ Seedance 2.0 : image-to-video uniquement." }, + _veo: { min: 4, max: 8, step: 1, tooltip: "" }, +}; +function getDurationConstraint(model) { + return DURATION_CONSTRAINTS[model] ?? DURATION_CONSTRAINTS._veo; +} + +// ─── Sync video_duration selon le modèle ────────────────────────────────────── +function setupKlingDurationSync(node) { + const modelWidget = getWidget(node, "model"); + const durationWidget = getWidget(node, "video_duration"); + if (!modelWidget || !durationWidget) return; + + /** Clamp une valeur dans [min, max] en respectant step. */ + const clampDuration = (v, { min, max, step }) => { + let clamped = Math.max(min, Math.min(max, parseInt(v) || min)); + // Pour step > 1 (ex. Kling 2.6 : step=5) : snap sur le multiple le plus proche + if (step > 1) { + const steps = Math.round((clamped - min) / step); + clamped = min + steps * step; + } + return Math.max(min, Math.min(max, clamped)); + }; + + /** Recalibre min/max/step et snappe la valeur si besoin. */ + const syncDuration = () => { + if (!node._nbIsVideoMode) return; + const c = getDurationConstraint(modelWidget.value); + if (durationWidget.options) { + durationWidget.options.min = c.min; + durationWidget.options.max = c.max; + durationWidget.options.step = c.step; + } + durationWidget.tooltip = c.tooltip; + const clamped = clampDuration(durationWidget.value, c); + if (durationWidget.value !== clamped) { + durationWidget.value = clamped; + if (durationWidget.callback) durationWidget.callback(clamped); + } + node.setDirtyCanvas(true); + }; + + node._nbSyncKlingDuration = syncDuration; + syncDuration(); + + // Hooker le changement de modèle → recalibrer la durée + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncDuration(); + }; +} +// ─── Sync batch_size selon provider et mode vidéo ───────────────────────── +function setupProviderBatchSync(node) { + const providerWidget = getWidget(node, "provider"); + const batchSizeWidget = getWidget(node, "batch_size"); + if (!providerWidget || !batchSizeWidget) return; + const syncBatchState = () => { + const isVideo = node._nbIsVideoMode === true; + // VERTEX image mode : batch autorisé (multi-projets JSON) + // Seul le mode vidéo verrouille batch_size à 1 + const shouldLock = isVideo; + batchSizeWidget.disabled = shouldLock; + if (shouldLock) batchSizeWidget.value = 1; + node.setDirtyCanvas(true); + }; + // Expose pour que les fonctions activateVideoMode / activateImageMode + // puissent déclencher une resynchronisation sans passer par le callback + // du widget provider. + node._nbSyncBatchState = syncBatchState; + syncBatchState(); + const origCallback = providerWidget.callback; + providerWidget.callback = function (...args) { + if (origCallback) origCallback.apply(this, args); + syncBatchState(); + }; +} +// ─── Sync image_size (résolution) selon le modèle vidéo ───────────────────── +// Seedance 2.0 : 480p / 720p / 1080p (pas de 4K) +// Autres modèles vidéo : 720p / 1080p uniquement (pas de 480p) +function setupVideoResolutionSync(node) { + const modelWidget = getWidget(node, "model"); + const imgSizeWidget = getWidget(node, "image_size"); + if (!modelWidget || !imgSizeWidget) return; + + const syncResolution = () => { + if (!node._nbIsVideoMode) return; + const model = modelWidget.value; + const isSeedance = SEEDANCE_MODELS.includes(model); + const isKling30 = KLING30_MODELS.includes(model); + + let allowedRes, defaultRes; + if (isSeedance) { + allowedRes = ["480p", "720p", "1080p"]; + defaultRes = "720p"; + } else if (isKling30) { + allowedRes = ["720p", "1080p", "4K"]; + defaultRes = "1080p"; + } else { + allowedRes = ["720p", "1080p"]; + defaultRes = "1080p"; + } + + if (imgSizeWidget.options?.values) imgSizeWidget.options.values = [...allowedRes]; + if (!allowedRes.includes(imgSizeWidget.value)) { + imgSizeWidget.value = defaultRes; + if (imgSizeWidget.callback) imgSizeWidget.callback(defaultRes); + } + // Tooltip sur le widget modèle pour indiquer image-to-video uniquement + if (modelWidget.options) { + modelWidget.options.tooltip = isSeedance + ? "⚠️ Image-to-video uniquement" + : ""; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncVideoResolution = syncResolution; + + // Hooker le changement de modèle → recalibrer la résolution + const origModelCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origModelCb) origModelCb.apply(this, args); + syncResolution(); + }; +} +// ─── Sync aspect_ratio et gpt2_image_quality selon le modèle ───────────── +function setupGPT2Sync(node) { + const modelWidget = getWidget(node, "model"); + const arWidget = getWidget(node, "aspect_ratio"); + if (!modelWidget || !arWidget) return; + + /** Retourne le ratio le plus proche supporté par GPT2. */ + function nearestGPT2AR(value) { + if (GPT2_ASPECT_RATIOS.includes(value)) return value; + return GPT2_NEAREST_AR[value] || "1:1"; + } + + /** Applique ou retire le filtre GPT2 sur le dropdown aspect_ratio. */ + const syncAR = () => { + const isGPT2 = (modelWidget.value === "GPT Image 2.0"); + if (isGPT2) { + if (arWidget.options?.values) arWidget.options.values = [...GPT2_ASPECT_RATIOS]; + const snapped = nearestGPT2AR(arWidget.value); + if (arWidget.value !== snapped) { + arWidget.value = snapped; + if (arWidget.callback) arWidget.callback(snapped); + } + } else { + // Restaure la liste complète selon le mode courant + const fullList = node._nbIsVideoMode ? VIDEO_ASPECT_RATIOS : IMAGE_ASPECT_RATIOS; + if (arWidget.options?.values) arWidget.options.values = [...fullList]; + } + node.setDirtyCanvas(true); + }; + + node._nbSyncGPT2AR = syncAR; + syncAR(); + + // Hooker le changement de modèle + const origCb = modelWidget.callback; + modelWidget.callback = function (...args) { + if (origCb) origCb.apply(this, args); + syncAR(); + }; +} +// ─── Factorisation des styles des boutons ON/OFF ────────────────────────── +// Évite de dupliquer 8 lignes de style à chaque toggle (Face Swap, Breast +// Refiner, Low Neck). Chaque bouton a sa propre palette "ON". +const TOGGLE_OFF_CSS = { + text: "OFF", + background: "#3a3a3a", + color: "#888", + border: "1.5px solid #666", + boxShadow: "none", +}; +/** + * Applique l'état visuel ON/OFF à un bouton bascule. + * @param {HTMLButtonElement} btn + * @param {boolean} on + * @param {{bg:string, text?:string, border:string, glow:string}} onStyle + */ +function setToggleVisual(btn, on, onStyle) { + if (on) { + btn.textContent = onStyle.text || "ON"; + btn.style.background = onStyle.bg; + btn.style.color = "#fff"; + btn.style.border = `1.5px solid ${onStyle.border}`; + btn.style.boxShadow = `0 0 8px ${onStyle.glow}`; + } else { + btn.textContent = TOGGLE_OFF_CSS.text; + btn.style.background = TOGGLE_OFF_CSS.background; + btn.style.color = TOGGLE_OFF_CSS.color; + btn.style.border = TOGGLE_OFF_CSS.border; + btn.style.boxShadow = TOGGLE_OFF_CSS.boxShadow; + } +} +const FS_ON_STYLE = { bg: "#00c853", border: "#00e676", glow: "rgba(0,200,83,0.5)" }; +const BR_ON_STYLE = { bg: "#c2185b", border: "#f50057", glow: "rgba(245,0,87,0.4)" }; +const LN_ON_STYLE = { bg: "#6a1b9a", border: "#ab47bc", glow: "rgba(171,71,188,0.4)" }; +// CSS de base partagé par les 3 boutons ON/OFF (même taille, même rayon) +const TOGGLE_BTN_BASE_CSS = ` + padding: 4px 18px; + border-radius: 14px; + border: 1.5px solid #666; + background: #3a3a3a; + color: #888; + font-weight: 700; + font-size: 11px; + cursor: pointer; + min-width: 55px; + letter-spacing: 0.5px; + transition: all 0.2s ease; +`; +// ─── Image / Video mode toggle ──────────────────────────────────────────── +function buildModeToggle(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #1565c0; + border-radius: 9px; + padding: 8px 10px 11px 10px; + background: linear-gradient(135deg, + rgba(21,101,192,0.14) 0%, + rgba(79,195,247,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Titre ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ GENERATION MODE"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #4fc3f7; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(79,195,247,0.45); + margin-bottom: 7px; + user-select: none; + transition: color 0.25s, text-shadow 0.25s; + `; + container.appendChild(titleEl); + // ── Séparateur ──────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #1565c0 40%, #1565c0 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Boutons IMAGE / VIDÉO côte à côte ───────────────────────────────── + const btnRow = document.createElement("div"); + btnRow.style.cssText = "display:flex; gap:8px;"; + function makeChoiceBtn(label, active) { + const btn = document.createElement("button"); + btn.textContent = label; + btn.style.cssText = ` + flex: 1; + padding: 6px 4px; + border-radius: 8px; + border: 1.5px solid ${active ? "#4fc3f7" : "#444"}; + background: ${active ? "rgba(79,195,247,0.18)" : "#252525"}; + color: ${active ? "#4fc3f7" : "#555"}; + font-weight: 700; + font-size: 11px; + cursor: pointer; + letter-spacing: 1px; + box-shadow: ${active ? "0 0 7px rgba(79,195,247,0.25)" : "none"}; + transition: all 0.2s ease; + `; + return btn; + } + const imgBtn = makeChoiceBtn("🖼 IMAGES", true); + const vidBtn = makeChoiceBtn("🎬 VIDÉO", false); + btnRow.appendChild(imgBtn); + btnRow.appendChild(vidBtn); + container.appendChild(btnRow); + // ── État ────────────────────────────────────────────────────────────── + let isVideoMode = false; + const GREY_IN_VIDEO = [ + "temperature", "top_p", "negative_prompt", + "fal_safety_tolerance", "fal_enable_web_search", + "use_search", "system_instructions", "batch_size", + "gpt2_image_quality", + ]; + // ── Grise/dégrise le bloc Automation Face Swap ─────────────────────── + function setFaceSwapGreyed(greyed) { + const fsW = node.widgets?.find(w => w.name === "nb_faceswap_automation"); + const el = fsW?.element; + if (!el) return; + el.style.opacity = greyed ? "0.22" : "1"; + el.style.pointerEvents = greyed ? "none" : "auto"; + el.style.filter = greyed ? "grayscale(80%) brightness(0.35)" : "none"; + app.graph.setDirtyCanvas(true, true); + } + function updateCombo(name, newValues, newDefault) { + const w = getWidget(node, name); + if (!w) return; + if (w.options?.values) w.options.values = [...newValues]; + if (!newValues.includes(w.value)) { + w.value = newDefault; + if (w.callback) w.callback(newDefault); + } + } + // ── Visibilité des widgets vidéo-only ───────────────────────────────── + // Ces widgets sont visibles SI ET SEULEMENT SI on est en mode VIDEO. + function updateVideoOnlyWidgets(visible) { + setWidgetVisible(node, "video_duration", visible); + setWidgetVisible(node, "video_generate_audio", visible); + } + function updateVideoDurationVisibility() { updateVideoOnlyWidgets(node._nbIsVideoMode === true); } + node._nbUpdateVideoDuration = updateVideoDurationVisibility; + // ── Activer le mode IMAGE ───────────────────────────────────────────── + function activateImageMode(initial = false) { + isVideoMode = false; + node._nbIsVideoMode = false; + imgBtn.style.border = "1.5px solid #4fc3f7"; + imgBtn.style.background = "rgba(79,195,247,0.18)"; + imgBtn.style.color = "#4fc3f7"; + imgBtn.style.boxShadow = "0 0 7px rgba(79,195,247,0.25)"; + vidBtn.style.border = "1.5px solid #444"; + vidBtn.style.background = "#252525"; + vidBtn.style.color = "#555"; + vidBtn.style.boxShadow = "none"; + container.style.border = "2px solid #1565c0"; + container.style.background = "linear-gradient(135deg, rgba(21,101,192,0.14) 0%, rgba(79,195,247,0.06) 100%)"; + titleEl.style.color = "#4fc3f7"; + titleEl.style.textShadow = "0 0 10px rgba(79,195,247,0.45)"; + // IMAGE_MODELS_DEFAULT = source de vérité (Python déclare image+vidéo + // pour la validation serveur, donc options.values n'est plus fiable) + const modelW = getWidget(node, "model"); + if (modelW) { + const vals = IMAGE_MODELS_DEFAULT; + if (modelW.options?.values) modelW.options.values = [...vals]; + if (!vals.includes(modelW.value)) { + modelW.value = vals[0]; + if (modelW.callback) modelW.callback(vals[0]); + } + if (modelW._imgOrigTooltip !== undefined) { + if (modelW.options) modelW.options.tooltip = modelW._imgOrigTooltip; + delete modelW._imgOrigTooltip; + } + } + updateCombo("aspect_ratio", IMAGE_ASPECT_RATIOS, "1:1"); + updateCombo("image_size", IMAGE_RESOLUTIONS, "2K"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "image_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, false); + // Re-synchronise batch_size et aspect_ratio (Kling) en mode image + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(false), 60); + if (!initial) { + syncNodeWidget(node, "video_mode_enabled", false); + app.graph.setDirtyCanvas(true, true); + } + } + // ── Activer le mode VIDÉO ───────────────────────────────────────────── + function activateVideoMode() { + isVideoMode = true; + node._nbIsVideoMode = true; + vidBtn.style.border = "1.5px solid #ce93d8"; + vidBtn.style.background = "rgba(206,147,216,0.18)"; + vidBtn.style.color = "#ce93d8"; + vidBtn.style.boxShadow = "0 0 7px rgba(206,147,216,0.3)"; + imgBtn.style.border = "1.5px solid #444"; + imgBtn.style.background = "#252525"; + imgBtn.style.color = "#555"; + imgBtn.style.boxShadow = "none"; + container.style.border = "2px solid #6a1b9a"; + container.style.background = "linear-gradient(135deg, rgba(106,27,154,0.14) 0%, rgba(206,147,216,0.06) 100%)"; + titleEl.style.color = "#ce93d8"; + titleEl.style.textShadow = "0 0 10px rgba(206,147,216,0.45)"; + // VIDEO_MODELS = source de vérité — pas de sauvegarde _imgOrigValues + // car options.values contient maintenant image+vidéo côté Python + const modelW = getWidget(node, "model"); + if (modelW) { + if (modelW.options?.values) modelW.options.values = [...VIDEO_MODELS]; + if (!VIDEO_MODELS.includes(modelW.value)) { + modelW.value = VIDEO_MODELS[0]; + if (modelW.callback) modelW.callback(VIDEO_MODELS[0]); + } + if (modelW.options?.tooltip) { + modelW._imgOrigTooltip = modelW.options.tooltip; + modelW.options.tooltip = ""; + } + } + updateCombo("aspect_ratio", VIDEO_ASPECT_RATIOS, "16:9"); + updateCombo("image_size", VIDEO_RESOLUTIONS, "1080p"); + const imgSizeW = getWidget(node, "image_size"); + if (imgSizeW) imgSizeW.label = "video_size"; + for (const name of GREY_IN_VIDEO) setWidgetLocked(node, name, true); + // Force batch_size = 1, synchronise aspect_ratio, durée et résolution selon le modèle + node._nbSyncBatchState?.(); + node._nbSyncKlingAspectRatio?.(); + node._nbSyncKlingDuration?.(); + node._nbSyncVideoResolution?.(); + updateVideoDurationVisibility(); + setTimeout(() => setFaceSwapGreyed(true), 60); + syncNodeWidget(node, "video_mode_enabled", true); + app.graph.setDirtyCanvas(true, true); + } + // ── Listeners ───────────────────────────────────────────────────────── + imgBtn.addEventListener("click", () => { if (isVideoMode) activateImageMode(); }); + vidBtn.addEventListener("click", () => { if (!isVideoMode) activateVideoMode(); }); + node._modeToggleAPI = { activateImageMode, activateVideoMode }; + // ── État initial SYNCHRONE (mode image par défaut) ──────────────────── + // Masquer video_duration AVANT d'ajouter le DOM widget évite un + // redimensionnement visible du node ~250 ms après le démarrage. + node._nbIsVideoMode = false; + updateVideoOnlyWidgets(false); + // ── Ajout DOM widget ────────────────────────────────────────────────── + const domWidget = node.addDOMWidget( + "nb_mode_toggle", "mode_toggle_div", container, + { serialize: false, hideOnZoom: false } + ); + if (domWidget) domWidget.computeSize = (w) => [w, 95]; + // ── Placer en PREMIER ───────────────────────────────────────────────── + if (domWidget) { + const idx = node.widgets.indexOf(domWidget); + if (idx > 0) { node.widgets.splice(idx, 1); node.widgets.unshift(domWidget); } + app.graph.setDirtyCanvas(true, true); + } + // ── Filtrage initial du dropdown "model" (mode image par défaut) ───── + // On ne fait QUE filtrer la liste — pas d'appel à activateImageMode() + // pour éviter de déclencher des callbacks qui perturbent la visibilité + // des widgets DOM (inputEl créés après le premier rendu). + setTimeout(() => { + const modelW = getWidget(node, "model"); + if (!modelW || node._nbIsVideoMode) return; + if (modelW.options?.values) modelW.options.values = [...IMAGE_MODELS_DEFAULT]; + if (!IMAGE_MODELS_DEFAULT.includes(modelW.value)) modelW.value = IMAGE_MODELS_DEFAULT[0]; + }, 200); + // ── Sync UI ↔ widget "video_mode_enabled" après chargement workflow ── + // Au chargement d'un workflow, ComfyUI restaure la valeur du widget + // caché `video_mode_enabled`, mais la variable locale isVideoMode reste + // à false. Résultat : l'UI montre IMAGES mais le backend reçoit + // video_mode_enabled=true → "Modèle vidéo inconnu : Nano Banana Pro". + // On fixe ça en synchronisant l'UI avec la valeur réelle du widget ~350ms + // après le onNodeCreated (délai suffisant pour que configure() ait injecté + // les valeurs sauvegardées). + setTimeout(() => { + const videoModeWidget = getWidget(node, "video_mode_enabled"); + const savedIsVideo = videoModeWidget?.value === true; + if (savedIsVideo && !node._nbIsVideoMode) { + // Workflow sauvegardé en mode vidéo → bascule l'UI en vidéo + activateVideoMode(); + } else { + // Force explicitement le widget à false pour éviter qu'une + // valeur "truthy" résiduelle (1, "true"…) passe côté Python + syncNodeWidget(node, "video_mode_enabled", false); + } + }, 350); +} +// ─── Automation Face Swap UI ────────────────────────────────────────────── +function buildFaceSwapUI(node) { + // ── Outer container ─────────────────────────────────────────────────── + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #e65c00; + border-radius: 9px; + padding: 9px 10px 16px 10px; + background: linear-gradient(135deg, + rgba(230,92,0,0.13) 0%, + rgba(255,140,0,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + transition: border-color 0.25s, background 0.25s; + `; + forwardWheelToCanvas(container); + // ── Title ───────────────────────────────────────────────────────────── + const titleEl = document.createElement("div"); + titleEl.textContent = "⚡ AUTOMATION FACE SWAP"; + titleEl.style.cssText = ` + font-weight: 700; + font-size: 11.5px; + color: #ff8c00; + letter-spacing: 2px; + text-align: center; + text-shadow: 0 0 10px rgba(255,140,0,0.45); + margin-bottom: 7px; + transition: color 0.25s, text-shadow 0.25s; + user-select: none; + `; + container.appendChild(titleEl); + // ── Separator ───────────────────────────────────────────────────────── + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #e65c00 40%, #e65c00 60%, transparent); + opacity: 0.55; + margin-bottom: 8px; + `; + container.appendChild(sep); + // ── Info hint ───────────────────────────────────────────────────────── + const hintEl = document.createElement("div"); + hintEl.textContent = "ℹ️ Image 1 = reference face · Image 2 = face to swap"; + hintEl.style.cssText = ` + font-size: 10px; + color: #999; + font-style: italic; + text-align: center; + margin-bottom: 8px; + user-select: none; + `; + container.appendChild(hintEl); + // ── Helper pour construire une ligne "label + bouton ON/OFF" ────────── + function makeToggleRow(labelText, tooltip, hidden = false) { + const row = document.createElement("div"); + row.style.cssText = ` + display: ${hidden ? "none" : "flex"}; + align-items: center; + gap: 8px; + ${hidden ? "margin-top: 8px; padding-top: 7px; border-top: 1px solid rgba(230,92,0,0.3);" : ""} + `; + const label = document.createElement("span"); + label.textContent = labelText; + label.title = tooltip; + label.style.cssText = ` + font-size: 12px; + color: #ccc; + flex: 1; + user-select: none; + `; + const btn = document.createElement("button"); + btn.textContent = "OFF"; + btn.title = tooltip; + btn.style.cssText = TOGGLE_BTN_BASE_CSS; + row.appendChild(label); + row.appendChild(btn); + return { row, btn }; + } + // ── Face Swap toggle ────────────────────────────────────────────────── + const { row: toggleRow, btn: toggleBtn } = makeToggleRow( + "Face Swap", + "Activate to run Automation Face Swap.\nImage 1 = reference face · Image 2 = face to swap", + false + ); + container.appendChild(toggleRow); + // ── Breast Refiner row (hidden until automation ON) ────────────────── + const { row: brRow, btn: brBtn } = makeToggleRow( + "Breast Refiner", + "This tool enhances breast shape by defining the upper curve for a more natural look. May trigger NSFW restrictions.", + true + ); + container.appendChild(brRow); + // ── Low Neck row (hidden until automation ON) ──────────────────────── + const { row: lnRow, btn: lnBtn } = makeToggleRow( + "Low Neck", + "Add a low neck, might be flagged as sensitive content.", + true + ); + container.appendChild(lnRow); + // ── Facial Expression section (hidden until automation ON) ─────────── + const EXPRESSIONS = [ + "Neutral", "Sensual", "Playful", "Subtle smile", "Smile", "Laugh", + ]; + const exprSection = document.createElement("div"); + exprSection.style.cssText = ` + display: none; + flex-direction: column; + gap: 6px; + margin-top: 8px; + padding-top: 7px; + border-top: 1px solid rgba(230,92,0,0.3); + `; + const exprTitleEl = document.createElement("div"); + exprTitleEl.textContent = "Facial Expression"; + exprTitleEl.style.cssText = ` + font-size: 11px; + font-weight: 600; + color: #aaa; + letter-spacing: 0.8px; + user-select: none; + `; + exprSection.appendChild(exprTitleEl); + const exprGrid = document.createElement("div"); + exprGrid.style.cssText = ` + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 4px; + `; + const exprBtns = {}; + function selectExpression(value) { + for (const [v, btn] of Object.entries(exprBtns)) { + const active = (v === value); + btn.style.background = active ? "rgba(255,140,0,0.35)" : "#2a2a2a"; + btn.style.color = active ? "#ff8c00" : "#888"; + btn.style.border = active ? "1.5px solid #e65c00" : "1.5px solid #444"; + btn.style.fontWeight = active ? "700" : "400"; + } + syncNodeWidget(node, "face_expression", value); + } + for (const value of EXPRESSIONS) { + const btn = document.createElement("button"); + btn.textContent = value; + btn.style.cssText = ` + padding: 4px 6px; + border-radius: 10px; + border: 1.5px solid #444; + background: #2a2a2a; + color: #888; + font-size: 10.5px; + cursor: pointer; + transition: all 0.15s ease; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; + btn.addEventListener("click", () => selectExpression(value)); + exprBtns[value] = btn; + exprGrid.appendChild(btn); + } + exprSection.appendChild(exprGrid); + container.appendChild(exprSection); + selectExpression("Neutral"); + // ── State ───────────────────────────────────────────────────────────── + let automationActive = false; + let breastRefinerActive = false; + let lowNeckActive = false; + const FS_HEIGHT_OFF = 115; + const FS_HEIGHT_ON = 300; + let _blockH = FS_HEIGHT_OFF; + // ── Face Swap toggle ────────────────────────────────────────────────── + toggleBtn.addEventListener("click", () => { + automationActive = !automationActive; + _blockH = automationActive ? FS_HEIGHT_ON : FS_HEIGHT_OFF; + setToggleVisual(toggleBtn, automationActive, FS_ON_STYLE); + if (automationActive) { + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + } else { + container.style.border = "2px solid #e65c00"; + container.style.background = "linear-gradient(135deg, rgba(230,92,0,0.13) 0%, rgba(255,140,0,0.06) 100%)"; + titleEl.style.color = "#ff8c00"; + titleEl.style.textShadow = "0 0 10px rgba(255,140,0,0.45)"; + brRow.style.display = "none"; + lnRow.style.display = "none"; + exprSection.style.display = "none"; + // Reset sub-toggles when automation is switched off + if (breastRefinerActive) { + breastRefinerActive = false; + setToggleVisual(brBtn, false, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", false); + } + if (lowNeckActive) { + lowNeckActive = false; + setToggleVisual(lnBtn, false, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", false); + } + } + applyAutomationState(node, automationActive); + syncNodeWidget(node, "face_swap_enabled", automationActive); + // Force la taille immédiatement (pas de latence au premier clic) + const newSize = node.computeSize(); + node.size[0] = Math.max(node.size[0], newSize[0]); + node.size[1] = newSize[1]; + app.graph.setDirtyCanvas(true, true); + }); + // ── Breast Refiner toggle ───────────────────────────────────────────── + brBtn.addEventListener("click", () => { + breastRefinerActive = !breastRefinerActive; + setToggleVisual(brBtn, breastRefinerActive, BR_ON_STYLE); + syncNodeWidget(node, "breast_refiner_enabled", breastRefinerActive); + app.graph.setDirtyCanvas(true); + }); + // ── Low Neck toggle ─────────────────────────────────────────────────── + lnBtn.addEventListener("click", () => { + lowNeckActive = !lowNeckActive; + setToggleVisual(lnBtn, lowNeckActive, LN_ON_STYLE); + syncNodeWidget(node, "low_neck_enabled", lowNeckActive); + app.graph.setDirtyCanvas(true); + }); + // ── Add DOM widget to node ──────────────────────────────────────────── + const domWidget = node.addDOMWidget("nb_faceswap_automation", "automation_div", container, { + serialize: false, + hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + // ── Restaure l'état sauvegardé dans le workflow ─────────────────────── + // Le DOM démarre à OFF par défaut ; on le réaligne sur les widgets Python + // pour que l'état visuel corresponde toujours à ce qui sera exécuté. + const _savedFS = getWidget(node, "face_swap_enabled")?.value === true; + if (_savedFS) { + automationActive = true; + _blockH = FS_HEIGHT_ON; + if (domWidget) domWidget.computeSize = (w) => [w, _blockH]; + setToggleVisual(toggleBtn, true, FS_ON_STYLE); + container.style.border = "2px solid #00c853"; + container.style.background = "linear-gradient(135deg, rgba(0,200,83,0.13) 0%, rgba(0,230,118,0.06) 100%)"; + titleEl.style.color = "#00e676"; + titleEl.style.textShadow = "0 0 10px rgba(0,230,118,0.55)"; + brRow.style.display = "flex"; + lnRow.style.display = "flex"; + exprSection.style.display = "flex"; + applyAutomationState(node, true); + } + // Breast Refiner et Low Neck : toujours OFF au démarrage. + // On réinitialise le widget Python même si le workflow les avait sauvegardés + // à true, pour éviter qu'ils se réactivent silencieusement entre sessions. + syncNodeWidget(node, "breast_refiner_enabled", false); + syncNodeWidget(node, "low_neck_enabled", false); + // breastRefinerActive et lowNeckActive restent false, boutons restent OFF. + // Masque les widgets Python cachés (IMMÉDIATEMENT, pas en setTimeout, pour + // éviter que le node soit dessiné grand puis rétréci juste après). + const HIDDEN_PY_WIDGETS = [ + "face_swap_enabled", "breast_refiner_enabled", "low_neck_enabled", + "face_expression", "video_mode_enabled", + ]; + for (const name of HIDDEN_PY_WIDGETS) { + const w = getWidget(node, name); + if (!w) continue; + w._fsOrigComputeSize = w.computeSize; + w.computeSize = () => [0, -4]; + w.hidden = true; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + } + app.graph.setDirtyCanvas(true, true); +} +// ─── Preset panel (10 slots, mode-aware, avec champ nom) ────────────────── +function buildPresetUI(node) { + const NUM_PRESETS = 10; + const container = document.createElement("div"); + container.style.cssText = ` + box-sizing: border-box; + border: 2px solid #37474f; + border-radius: 9px; + padding: 8px 10px 10px 10px; + background: linear-gradient(135deg, + rgba(55,71,79,0.14) 0%, + rgba(96,125,139,0.06) 100%); + font-family: 'Segoe UI', Arial, sans-serif; + width: 100%; + overflow: hidden; + `; + forwardWheelToCanvas(container); + const titleEl = document.createElement("div"); + titleEl.textContent = "💾 PRESETS"; + titleEl.style.cssText = ` + font-weight: 700; font-size: 11.5px; color: #90a4ae; + letter-spacing: 2px; text-align: center; + margin-bottom: 7px; user-select: none; + `; + container.appendChild(titleEl); + const sep = document.createElement("div"); + sep.style.cssText = ` + height: 1px; + background: linear-gradient(to right, transparent, #37474f 40%, #37474f 60%, transparent); + opacity: 0.55; margin-bottom: 7px; + `; + container.appendChild(sep); + const list = document.createElement("div"); + list.style.cssText = "display: flex; flex-direction: column; gap: 4px;"; + container.appendChild(list); + const slotRows = {}; + const slotInputs = {}; + function markSlotFilled(n, filled, name) { + const row = slotRows[n]; + const input = slotInputs[n]; + if (!row) return; + row.style.border = filled ? "1px solid rgba(79,195,247,0.3)" : "1px solid #2a2a2a"; + row.style.background = filled ? "rgba(79,195,247,0.04)" : "#1a1a1a"; + if (input && name !== undefined) input.value = name || ""; + } + function buildSlot(n) { + const row = document.createElement("div"); + row.style.cssText = ` + display: flex; align-items: center; gap: 4px; + padding: 3px 5px; border-radius: 6px; + border: 1px solid #2a2a2a; background: #1a1a1a; + transition: border 0.2s, background 0.2s; + `; + slotRows[n] = row; + const label = document.createElement("span"); + label.textContent = `${n < 10 ? " " : ""}${n}`; + label.style.cssText = ` + font-size: 9.5px; color: #555; min-width: 14px; + user-select: none; font-weight: 700; font-variant-numeric: tabular-nums; + `; + const nameInput = document.createElement("input"); + nameInput.type = "text"; + nameInput.placeholder = `preset ${n}`; + nameInput.style.cssText = ` + flex: 1; min-width: 0; + background: #111; border: 1px solid #333; border-radius: 4px; + color: #aaa; font-size: 9.5px; padding: 2px 5px; + outline: none; font-family: 'Segoe UI', Arial, sans-serif; + `; + nameInput.addEventListener("focus", () => nameInput.style.borderColor = "#546e7a"); + nameInput.addEventListener("blur", () => nameInput.style.borderColor = "#333"); + nameInput.addEventListener("keydown", e => e.stopPropagation()); + slotInputs[n] = nameInput; + const btnBase = ` + padding: 2px 8px; border-radius: 4px; font-size: 9px; + font-weight: 700; cursor: pointer; white-space: nowrap; + transition: all 0.15s ease; letter-spacing: 0.4px; + `; + const saveBtn = document.createElement("button"); + saveBtn.textContent = "SAVE"; + saveBtn.title = `Sauvegarder dans le slot ${n}`; + saveBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + const loadBtn = document.createElement("button"); + loadBtn.textContent = "LOAD"; + loadBtn.title = `Charger le slot ${n}`; + loadBtn.style.cssText = btnBase + "border: 1px solid #444; background: #252525; color: #666;"; + row.appendChild(label); + row.appendChild(nameInput); + row.appendChild(saveBtn); + row.appendChild(loadBtn); + list.appendChild(row); + saveBtn.addEventListener("click", async () => { + const params = { preset_name: nameInput.value.trim() }; + for (const w of node.widgets || []) { + if (w.name && w.value !== undefined + && w.type !== "button" && w.type !== "dom_widget" + && !w.name.startsWith("nb_")) { + params[w.name] = w.value; + } + } + try { + const res = await fetch("/nb_aio/save_preset", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ slot: n, params }), + }); + const data = await res.json(); + if (data.success) { + markSlotFilled(n, true, params.preset_name); + saveBtn.style.cssText = btnBase + "border:1px solid #00c853; background:#1b5e20; color:#69f0ae;"; + setTimeout(() => { + saveBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + } + } catch (e) { console.error("[NB Presets] Save error:", e); } + }); + loadBtn.addEventListener("click", async () => { + try { + const res = await fetch("/nb_aio/load_presets"); + const data = await res.json(); + if (!data.success) return; + const preset = data.presets?.[String(n)]; + if (!preset) return; + const isVideo = preset.video_mode_enabled === true; + if (isVideo && !node._nbIsVideoMode) { + node._modeToggleAPI?.activateVideoMode(); + } else if (!isVideo && node._nbIsVideoMode) { + node._modeToggleAPI?.activateImageMode(); + } + if (preset.preset_name !== undefined) { + nameInput.value = preset.preset_name || ""; + } + markSlotFilled(n, true, preset.preset_name); + const SKIP = new Set(["video_mode_enabled", "preset_name"]); + for (const [key, value] of Object.entries(preset)) { + if (SKIP.has(key)) continue; + syncNodeWidget(node, key, value); + } + loadBtn.style.cssText = btnBase + "border:1px solid #2962ff; background:#0d47a1; color:#82b1ff;"; + setTimeout(() => { + loadBtn.style.cssText = btnBase + "border:1px solid #444; background:#252525; color:#666;"; + }, 900); + app.graph.setDirtyCanvas(true, true); + } catch (e) { console.error("[NB Presets] Load error:", e); } + }); + } + for (let i = 1; i <= NUM_PRESETS; i++) buildSlot(i); + const PANEL_H = 368; + const domWidget = node.addDOMWidget("nb_presets_ui", "presets_div", container, { + serialize: false, hideOnZoom: false, + }); + if (domWidget) domWidget.computeSize = (w) => [w, PANEL_H]; + fetch("/nb_aio/load_presets") + .then(r => r.json()) + .then(data => { + if (!data.success) return; + for (let i = 1; i <= NUM_PRESETS; i++) { + const p = data.presets?.[String(i)]; + if (p) markSlotFilled(i, true, p.preset_name); + } + }) + .catch(() => {}); +} +// ─── Prompt widget colour coding ────────────────────────────────────────── +function stylePromptWidgets(node) { + setTimeout(() => { + const pos = getWidget(node, "prompt"); + if (pos?.inputEl) { + pos.inputEl.style.borderLeft = "3px solid #00c853"; + pos.inputEl.style.paddingLeft = "6px"; + pos.inputEl.style.borderRadius = "3px"; + } + const neg = getWidget(node, "negative_prompt"); + if (neg?.inputEl) { + neg.inputEl.style.borderLeft = "3px solid #e53935"; + neg.inputEl.style.paddingLeft = "6px"; + neg.inputEl.style.borderRadius = "3px"; + } + }, 200); +} +// ─── Extension registration ─────────────────────────────────────────────── +app.registerExtension({ + name: "NanoBananaAIO.FaceSwap", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "NanoBananaAIO") return; + const onCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onCreated?.apply(this, arguments); + const node = this; + stylePromptWidgets(node); + // Mode toggle en premier (synchrone) — place le widget tout en haut + buildModeToggle(node); + setTimeout(() => setupKlingAspectRatioSync(node), 500); + setTimeout(() => setupKlingDurationSync(node), 500); + setTimeout(() => setupProviderBatchSync(node), 500); + setTimeout(() => setupGPT2Sync(node), 500); + setTimeout(() => setupVideoResolutionSync(node), 500); + setTimeout(() => buildFaceSwapUI(node), 400); + setTimeout(() => buildPresetUI(node), 450); + // Nettoyage tardif des widgets preset hérités (autre JS) + setTimeout(() => { + if (!node.widgets) return; + const KEEP = new Set([ + "nb_faceswap_automation", "nb_presets_ui", "nb_mode_toggle", + "face_expression", "face_swap_enabled", "breast_refiner_enabled", + "low_neck_enabled", "video_mode_enabled", + ]); + const isLegacy = (w) => { + if (!w.name) return false; + if (KEEP.has(w.name)) return false; + if (w.name.startsWith("nb_")) return false; + const n = w.name.toLowerCase(); + return ( + w.type === "button" || + n.includes("preset") || + n.includes("slot") + ); + }; + for (let i = node.widgets.length - 1; i >= 0; i--) { + const w = node.widgets[i]; + if (!isLegacy(w)) continue; + if (w.inputEl) w.inputEl.style.display = "none"; + if (w.element) w.element.style.display = "none"; + node.widgets.splice(i, 1); + } + // Force-hide des widgets Python automation (canvas widgets LiteGraph) + for (const name of ["face_expression", "face_swap_enabled", + "breast_refiner_enabled", "low_neck_enabled", + "video_mode_enabled"]) { + const w = getWidget(node, name); + if (!w) continue; + w.hidden = true; + w.computeSize = () => [0, -4]; + if (w.inputEl) { try { w.inputEl.remove(); } catch (_) {} w.inputEl = null; } + if (w.element) { try { w.element.remove(); } catch (_) {} w.element = null; } + } + app.graph.setDirtyCanvas(true, true); + }, 1200); + // ── Restauration de la taille sauvegardée (workflow.json) ─────────── + // Les setTimeouts ci-dessus ajoutent des DOM widgets et appellent + // setDirtyCanvas, ce qui peut écraser la taille restaurée par + // configure(). On ré-applique la taille sauvegardée après le dernier + // setTimeout (1200ms) avec une petite marge. + setTimeout(() => { + if (node._nbSavedSize && Array.isArray(node._nbSavedSize)) { + node.size[0] = node._nbSavedSize[0]; + node.size[1] = node._nbSavedSize[1]; + app.graph.setDirtyCanvas(true, true); + } else { + // Nouveau node (jamais sauvegardé) — applique une taille + // par défaut généreuse pour que les prompt boxes soient + // utilisables sans avoir à redimensionner manuellement. + const DEFAULT_W = 520; + const DEFAULT_H = 900; + if (node.size[0] < DEFAULT_W) node.size[0] = DEFAULT_W; + if (node.size[1] < DEFAULT_H) node.size[1] = DEFAULT_H; + app.graph.setDirtyCanvas(true, true); + } + }, 1300); + }; + // ── Hook onConfigure : capture la taille sauvée dans le workflow ───── + // configure(info) est appelé par LiteGraph lors de la restauration d'un + // workflow. info.size contient la taille que l'utilisateur avait à la + // session précédente. On la stocke pour la ré-appliquer après que les + // DOM widgets aient fini leur setup. + const onConfigure = nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure = function (info) { + const r = onConfigure?.apply(this, arguments); + try { + if (info && Array.isArray(info.size) && info.size.length >= 2) { + this._nbSavedSize = [info.size[0], info.size[1]]; + } + } catch (_) { /* noop */ } + return r; + }; + }, +}); \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/js/nb_aio_presets.js b/aiorbust-ofm-pack-main/js/nb_aio_presets.js new file mode 100644 index 0000000000000000000000000000000000000000..f98055422bafd176db23cbc315e6b8b9d8398eba --- /dev/null +++ b/aiorbust-ofm-pack-main/js/nb_aio_presets.js @@ -0,0 +1,195 @@ +/** + * NanoBananaAIO — Preset UI + * Bouton Save/Load presets directement dans le node. + */ + +import { app } from "../../scripts/app.js"; + +const PRESET_KEYS = [ + "provider", + "prompt", + "image_size", + "model", + "batch_size", + "use_search", + "system_instructions", + "aspect_ratio", + "temperature", + "top_p", + "fal_safety_tolerance", + "fal_enable_web_search", + "disable_safety_threshold", + "vertex_location", +]; + +let _presetsCache = {}; + +async function loadPresetsFromServer() { + try { + const resp = await fetch("/nb_aio/load_presets"); + const data = await resp.json(); + if (data.success) { + _presetsCache = data.presets || {}; + } + } catch (e) { + console.warn("[NB AIO Presets] Impossible de charger :", e); + } +} + +loadPresetsFromServer(); + +function getWidgetValue(node, name) { + return node.widgets?.find(w => w.name === name)?.value; +} + +function setWidgetValue(node, name, value) { + const w = node.widgets?.find(w => w.name === name); + if (!w) return; + w.value = value; + if (w.callback) w.callback(value); + if (w.inputEl) w.inputEl.value = value; +} + +function collectNodeParams(node) { + const params = {}; + for (const key of PRESET_KEYS) { + const val = getWidgetValue(node, key); + if (val !== undefined) params[key] = val; + } + return params; +} + +function applyPresetToNode(node, data) { + for (const [key, value] of Object.entries(data)) { + if (PRESET_KEYS.includes(key)) { + setWidgetValue(node, key, value); + } + } + app.graph.setDirtyCanvas(true, true); +} + +app.registerExtension({ + name: "NanoBananaAIO.Presets", + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "NanoBananaAIO") return; + + const onCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onCreated?.apply(this, arguments); + const node = this; + setTimeout(() => { + buildPresetUI(node); + }, 200); + }; + }, +}); + +function buildPresetUI(node) { + + // ── PRESET SLOT selector ────────────────────────────────────── + const slotWidget = node.addWidget( + "combo", + "Preset Slot", + "1", + (value) => {}, + { + values: ["1", "2", "3", "4", "5"], + serialize: false, + } + ); + + // ── BOUTON SAVE ─────────────────────────────────────────────── + node.addWidget( + "button", + "💾 Save current settings to preset slot", + null, + async () => { + const slot = parseInt(slotWidget.value); + const params = collectNodeParams(node); + + showStatus(node, "⏳ Saving...", "#aaaaaa"); + + try { + const resp = await fetch("/nb_aio/save_preset", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ slot, params }), + }); + const data = await resp.json(); + + if (data.success) { + _presetsCache[String(slot)] = data.params; + showStatus(node, `✅ Preset ${slot} saved !`, "#4caf50"); + } else { + showStatus(node, `❌ Error: ${data.error}`, "#f44336"); + } + } catch (e) { + showStatus(node, "❌ Network error", "#f44336"); + console.error("[NB AIO Presets]", e); + } + }, + { serialize: false } + ); + + // ── BOUTON LOAD ─────────────────────────────────────────────── + node.addWidget( + "button", + "📂 Load preset slot into node", + null, + async () => { + const slot = slotWidget.value; + let cached = _presetsCache[slot]; + + if (!cached) { + await loadPresetsFromServer(); + cached = _presetsCache[slot]; + } + + if (!cached) { + showStatus(node, `⚠️ Slot ${slot} is empty`, "#ff9800"); + return; + } + + applyPresetToNode(node, cached); + const preview = (cached.prompt || "").slice(0, 40); + showStatus(node, `📂 Preset ${slot} loaded: ${preview}…`, "#2196f3"); + }, + { serialize: false } + ); + + // ── WIDGET STATUS ───────────────────────────────────────────── + const statusWidget = node.addWidget( + "text", + "nb_preset_status", + "", + () => {}, + { + serialize: false, + multiline: false, + } + ); + statusWidget.label = "⬆ preset info"; + statusWidget.disabled = true; + + node._nbStatusWidget = statusWidget; + node.setSize([node.size[0], node.computeSize()[1]]); +} + +function showStatus(node, msg, color = "#aaa") { + if (!node._nbStatusWidget) return; + node._nbStatusWidget.value = msg; + + if (node._nbStatusWidget.inputEl) { + node._nbStatusWidget.inputEl.style.color = color; + } + + clearTimeout(node._nbStatusTimer); + node._nbStatusTimer = setTimeout(() => { + if (node._nbStatusWidget) { + node._nbStatusWidget.value = ""; + } + }, 4000); + + app.graph.setDirtyCanvas(true); +} \ No newline at end of file diff --git a/aiorbust-ofm-pack-main/js/nb_video_preview.js b/aiorbust-ofm-pack-main/js/nb_video_preview.js new file mode 100644 index 0000000000000000000000000000000000000000..03187030768e4a6c62107b1fd7c08ec22172831a --- /dev/null +++ b/aiorbust-ofm-pack-main/js/nb_video_preview.js @@ -0,0 +1,364 @@ +/** + * nb_video_preview.js + * Injecte un vrai player